Enumeración rápida en NSArray de cadenas literales

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?

preguntado el 09 de marzo de 12 a las 17:03

I tested your code and it works as expected. So, is this your actual code? Or do you initialize the array in one location in your code and loop through it in another location? -

One possibility is that you have the assignment to "array" and the use of it in different locations. So "array" went conceptually out of scope and was GCed before you tried to reference it. I'm not yet familiar enough with ARC to know in what scenarios this could happen, but I'm sure there are a bunch. -

1 Respuestas

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.

respondido 09 mar '12, 17:03

Of course this wasn't my production code... I distilled it down to the example above because I thought the problem was with the string literals. The actual problem was within the for-in loop I was calling a method that expected an array as the argument, not a string. So, mistake was boneheaded. (Must find more coffee!) - Edelaney05

Yeah, I sometimes do that. Strip the code down and then add back in piece by piece until I get the error. Seems to work well. - Aarón Hayman

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.