Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fast Enumeration With an NSMutableArray that holds an NSDictionary

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?

like image 915
Alan Storm Avatar asked Feb 19 '10 23:02

Alan Storm


People also ask

Is it faster to iterate through an NSArray or an NSSet?

Yes, NSArray is faster than NSSet for simply holding and iterating. As little as 50% faster for constructing and as much as 500% faster for iterating.

What is fast enumeration in Objective C?

Fast Enumeration was introduced into Objective-C back in the 10.5 days. It's the feature that lets you succinctly iterate through a collection: NSArray *strings = [NSArray arrayWithObjects: @"greeble", @"bork", @"hoover", nil]; for (NSString *thing in strings) { NSLog (@"Woo!

What is the difference between NSDictionary and NSMutableDictionary?

Main Difference is:NSMutableDictionary is derived from NSDictionary, it has all the methods of NSDictionary. NSMutableDictionary is mutable( can be modified) but NSDictionary is immutable (can not be modified).


1 Answers

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.

like image 83
andyvn22 Avatar answered Nov 04 '22 00:11

andyvn22