È possibile utilizzare l'enumerazione rapida con un NSArray che contiene un NSDictionary?
Sto eseguendo alcune esercitazioni in Objective C e il seguente codice lancia la console in modalità 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);
}
Se sostituisco il ciclo di enumerazione veloce con un ciclo di conteggio tradizionale
int count = [myObjects count];
for(int i=0;i<count;i++)
{
id item;
item = [myObjects objectAtIndex:i];
NSLog(@"Found an Item: %@",item);
}
L'applicazione viene eseguita senza un arresto anomalo e il dizionario viene visualizzato nella finestra della console.
Si tratta di una limitazione di Fast Enumeration o mi manca qualche sottilmente della lingua? Ci sono altri trucchi quando si annidano raccolte come questa?
Per i punti bonus, come ho potuto usare GDB per eseguire il debug di questo io stesso?
risposte:
11 per risposta № 1Oops! arrayWithObjects:
ha bisogno di essere nil-terminato. Il seguente codice funziona perfettamente:
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);
}
Non sono sicuro del motivo per cui l'utilizzo di un loop tradizionale ha nascosto questo errore.