Glenn
Glenn

Reputation: 2806

For loops in Objective-C

counter = [myArray count];
for (i = 0 ; i < count ;  i++) {
     [[anotherArray objectAtIndex:i] setTitle:[myArray 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.)

Upvotes: 1

Views: 245

Answers (2)

bbum
bbum

Reputation: 162712

Use a block.

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

Upvotes: 5

anon
anon

Reputation:

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.

Upvotes: 6

Related Questions