Fast Enumeration With an NSMutableArray that holds an NSDictionary

17,177

Oops! arrayWithObjects: needs to be nil-terminated. The following code runs just fine:

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);
}

I'm not sure why using a traditional loop hid this error.

Share:
17,177
Alan Storm
Author by

Alan Storm

Portland based Web Developer/Programmer/Engineer. Projects include No Frills Magento Layout, the only Magento layout book you'll ever need and Commerce Bug, the debugging extension for the Magento Ecommerce system. If you're interested in low cost, in-depth mentoring/tutoring, checkout my Patreon campaign.

Updated on June 04, 2022

Comments

  • Alan Storm
    Alan Storm almost 2 years

    Is it possible to use fast enumeration with an NSArray that contains an NSDictionary?

    I'm running through some Objective C tutorials, and the following code kicks the console into GDB mode

    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);
    }
    

    If I replace the fast enumeration loop with a traditional counting loop

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

    The application runs without a crash, and the dictionary is output to the console window.

    Is this a limitation of Fast Enumeration, or am I missing some subtly of the language? Are there other gotchas when nesting collections like this?

    For bonus points, how could I used GDB to debug this myself?

  • Alan Storm
    Alan Storm about 14 years
    Ah, one of my favorite Cisms. "The thing you thought was working correctly shouldn't have been". Thanks for the novice advice!
  • Nico
    Nico about 14 years
    If you turn on -Wformat (“Typecheck calls to printf/scanf” in Xcode), the compiler will warn about this. If you also turn on -Werror (“Treat Warnings as Errors” in Xcode), the compiler will fail the compilation over this mistake.