Search code examples
objective-cfast-enumeration

Fast Enumeration on NSArray of string literals


Using ARC...

NSArray *array = [NSArray arrayWithObjects:@"dog", @"cat", @"mouse", nil];

for(NSString *animal in array) {
    NSLog(@"animal = %@", animal);
}

Yields an index out of bounds error.

*** -[__NSArrayM objectAtIndex:]: index 0 beyond bounds for empty array

What bonehead mistake have I made?


Solution

  • The code you've shown is fine. I just ran it under ARC and it completed successfully. Are you sure the error is for that code and not another portion of your code?

    A couple thoughts come to mind: the variable 'array' is pretty generic. Is it interfering with other local/instance variables? It shouldn't matter if the code is right next to each other, but if you've declared it in one place and are executing the for loop in another, you might not be executing the same 'array' as you think. Isolate this code in another class/method/whatever and see how it runs.

    Another thought: Fast Enumeration won't enumerate zero length arrays (it checks first). This is why I think you're mistaking the error for the wrong line of code.