2010-02-19 19 views
5

¿Es posible usar la enumeración rápida con un NSArray que contiene un NSDictionary?Enumeración rápida con un NSMutableArray que contiene un NSDictionary

Estoy corriendo a través de algunos tutoriales Objective C, y el siguiente código tira la consola en modo de GDB

NSMutableArray *myObjects = [NSMutableArray array]; 
NSArray *theObjects = [NSArray arrayWithObjects:@"easy as 1",@"easy as two", @"Easy as Three"]; 
NSArray *theKeys = [NSArray arrayWithObjects:@"A",@"B",@"C"];  
NSDictionary *theDict = [NSDictionary dictionaryWithObjects:theObjects forKeys:theKeys]; 
[myObjects addObject:theDict]; 

for(id item in myObjects) 
{ 
    NSLog(@"Found an Item: %@",item); 
} 

Si sustituyo el bucle de enumeración rápida con un bucle de conteo tradicional

int count = [myObjects count]; 
for(int i=0;i<count;i++) 
{ 
    id item; 
    item = [myObjects objectAtIndex:i]; 
    NSLog(@"Found an Item: %@",item); 
} 

La aplicación se ejecuta sin fallas y el diccionario se envía a la ventana de la consola.

¿Es esta una limitación de la enumeración rápida, o me falta algo sutilmente del lenguaje? ¿Hay otros problemas al anidar colecciones como esta?

Para obtener puntos de bonificación, ¿cómo podría usar GDB para depurar esto por mi cuenta?

Respuesta

10

¡Uy! arrayWithObjects: debe terminarse en cero. El siguiente código funciona muy bien:

NSMutableArray *myObjects = [NSMutableArray array]; 
NSArray *theObjects = [NSArray arrayWithObjects:@"easy as 1",@"easy as two", @"Easy as Three",nil]; 
NSArray *theKeys = [NSArray arrayWithObjects:@"A",@"B",@"C",nil];  
NSDictionary *theDict = [NSDictionary dictionaryWithObjects:theObjects forKeys:theKeys]; 
[myObjects addObject:theDict]; 

for(id item in myObjects) 
{ 
    NSLog(@"Found an Item: %@",item); 
} 

No estoy seguro de por qué el uso de un bucle tradicional ocultó este error.

+0

Ah, uno de mis Cisms favoritos. "Lo que creías que estaba funcionando correctamente no debería haber sido". Gracias por el consejo de novato! –

+3

Si enciende -Wformat ("Typecheck llama a printf/scanf" en Xcode), el compilador advertirá sobre esto. Si también enciende -Werror ("Tratar advertencias como errores" en Xcode), el compilador fallará la compilación sobre este error. –

+0

Gracias Peter, ¡muy útil! –

Cuestiones relacionadas