繁体   English   中英

在objective-c中获取for语句中的数组索引

[英]get the array index in for statement in objective-c

我被困在一个愚蠢的混乱中......
我不仅要获取数组的值,还要获取值的索引。
在PHP中它很简单: foreach($array as $key->$value)这里$ key将包含索引值。
目标c中没有类似的方法吗?
我怎么能做到这一点? 请帮忙! :((

不像php那样的数组编号为0大小的数组。 我想你在谈论字典。 如果是这样,您可以使用[dict allKeys]获取密钥数组。 所以像这样的东西应该工作:

for(id key in [dict allKeys]){
  id value = [dict objectForKey:key];
}

如果你在iOS4上,你可以做到

[array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
                                   {
                                       NSLog(@"%@ is at index %u", obj, idx);
                                   }];

在iOS 3.x上你可以做到

NSUInteger idx = 0;
for (id obj in array)
{
    NSLog(@"%@ is at index %u", obj, idx);
    idx++
}
for (i=0;i<array.count;i++)
{
  NSLog(@"Index=%d , Value=%@",i,[array objectAtIndex:i]);
}

使用它更简单......

快乐的编码......

我无法测试它,但我认为我确实做了类似的事情。 从这个维基看起来你可以做类似的事情

for(id key in d) {
    NSObject *obj = [d objectForKey:key];      // We use the (unique) key to access the (possibly non-unique) object.
    NSLog(@"%@", obj);
}
int arraySize = array.count;
// No need to calculate count/size always
for (int i=0; i<arraySize; i++)
{
    NSLog(@"Index=%d , Value=%@",i,[array objectAtIndex:i]);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM