Travis Griggs
Travis Griggs

Reputation: 22272

idiomatic way to enumerate NSArray by both index and element

I need to do something similar to python's enumerate() function with an NSArray in iOS (I have to build NSIndexPath objects as well as examine the object).

I don't see a built in method for doing something like this (i.e. no NSArray equivalent of NSDictionary's enumerateKeysAndObjectsUsingBlock: method). Which leaves me with two general approaches I can think of.

for (NSUInteger index = 0; index < mySequence.count; index++) {
    MyElementType *element = mySequence[index];
    //
    // code that works with both index and element
    //
}

or

NSUInteger index = 0;
for (MyElementType *element in mySequence) {
    //
    // code that works with both index and element
    //
    index++;
}

Is there a good reason to prefer on or the other? Or is there a third approach that is better than either of these?

Upvotes: 2

Views: 81

Answers (1)

gagarwal
gagarwal

Reputation: 4244

There is following API present in NSArray:

- (void)enumerateObjectsUsingBlock:(void (^)(id obj, NSUInteger idx, BOOL *stop))

Upvotes: 4

Related Questions