NSArray Multiple Enumeration

Let's say I have three arrays of the same size. I have to do something with all the objects. If I used a standard C array, I would write something like

for (i = 0; i < size; i++) {
    doSomething(array1[i]);   // or [[array1 objectAtIndex:i] doSomething];
    doSomethingElse(array2[i]);   // or [[array2 objectAtIndex:i] doSomethingElse];
    doSomethingReallySpecial(array3[i]);   // or [[array3 objectAtIndex:i] doSomethingReallySpecial];
}

With Objective-C, we got more options for cycling through objects in NSArray: fast enumeration, block based enumeration, and the use of counters. Which should I use and why? Who cares?

Edit
Actually this question can be formulated as follows: if you need to use the index of an array element, should you use an enumeration?

+5
source share
2 answers

, . , .

, (.. for(id i in array)) . C-, -[NSArray enumerateObjectsUsingBlock:] , zip . , C- , , , , .

, , , , GCD , .

0

NSEnumerator . - , , - .

. :

- (void) doSomethingToFruits:(void(^)(id,NSUInteger,BOOL*))block
{
    [apples enumerateObjectsUsingBlock:block];
    [bananas enumerateObjectsUsingBlock:block];
    [kiwis enumerateObjectsUsingBlock:block];
}

options enumerateObjectsUsingBlock:options: .

-, , , NSFastEnumeration , , ( - - ), :

- (void) addObjectsFromCollection:(id<NSFastEnumeration>)coll
{
    for (id obj in coll) [self addObject:obj];
}

, -, . , , , , , , , , .

:

, block .

+4
source

All Articles