开发者

For loops in Objective-C

counter = [myArray count];
for (i = 0 ; i < count ;  i++) {
     [[anotherArray objectAtIndex:i] setTitle:[my开发者_StackOverflow中文版Array objectAtIndex:i]];
}

I would like to do it the objective C 2.0 way but can't seem to find how to access the index 'i' (if that's possible anyway).

for (NSString *myString in myArray) {
     [[anotherArray objectAtIndex:i] setTitle: myString];
}

(Please forgive any typos; I'm currently not behind my Mac so this is out of my head.)


To do this you have to keep track of the index yourself:

NSUInteger index = 0;
for (NSString *myString in myArray) {
    [[anotherArray objectAtIndex: index] setTitle: myString];
    ++index;
}

Maybe in this case an old-fashioned for loop with an index is the better choice though. Unless you are trying to use fast enumeration for performance reasons here.

But it would be probably even better to restructure the code so that you don’t have to copy the strings from myArray to the title property of the objects in anotherArray manually.


Use a block.

[myArray enumerateObjectsUsingBlock ^(id obj, NSUInteger idx, BOOL *stop) {
        [[anotherArray objectAtIndex: idx] setTitle: obj];
}];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜