0

I have an NSMutableArray of NSNumbers, I want to enumerate through all of them with Objective-C styled enumeration. Here's what I've done so far.

for ( NSNumber* number in array )
{
    //some code
}

I want to be able to recognize the first object fast, I am able to do this of course,

if ( [array indexOfObject:number] == 0 )
{
    //if it's the first object
}

Is there any way to do this faster? There's of course the old-fashioned C style way, and remove the object from array first, and then put it back after enumeration. Just want to know if there's a better technic.

Shane Hsu
  • 7,937
  • 6
  • 39
  • 63

3 Answers3

4

You can try using a method that provides the index of the object currently being enumerated:

[array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    if (idx == 0) {
        // this is the first object
    }
}];

Or if you simply want to access the first object of an array:

id obj = [array objectAtIndex:0];

or with the new Objective-C style/syntax:

id obj = array[0];
  • I am always so confused when I see the new Objective-C array indexing syntax... and I have Java/C++ background. – Sulthan Jan 12 '13 at 11:18
3

This solution is faster than accessing and comparing the first array element:

BOOL firstIteration = YES;
for (NSNumber *number in array) {
    if (firstIteration) {
        // Handle first iteration
        firstIteration = NO;
    }
    // Do something
}
Attila H
  • 3,616
  • 2
  • 24
  • 37
0

In fast enumeration you cant alter the array. So if you want to remove you have to use old style for(;;) loop.

To find the first object simply use [array objectAtIndex:0]

Anoop Vaidya
  • 46,283
  • 15
  • 111
  • 140