Friday, May 6, 2011

NSDictionary iteration using NSEnumerator

An example for iterating NSDictionary object using NSEnumerator.
An NSDictionary object is created with some keys and values (all NSString objects).
NSEnumerator object is created from NSDictionary object by calling NSDictionary:keyEnumerator: method.

Following code is collected from http://www.cocoadev.com/index.pl?NSDictionary



int main(int argc, const char *argv[])
{
    NSDictionary *dict;
    NSEnumerator *enumerator;
    id key;
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    
    dict = [NSDictionary dictionaryWithObjectsAndKeys:
                   @"A beverage prepared by heating cocoa with water/milk",
                   @"cocoa", 
                   @"http://www.cocoadev.com/",
                   @"cocoadev", 
                   @"4 : a list (as of items of data or words) stored in a                         computer for reference (as for information retrieval                         or word processing)",
                   @"dictionary",
                   nil];
    
    // printf("entry for cocoa: %s\n\n",
    //        [[dict objectForKey:@"cocoa"]cString]);
    // Use of the cString method is discouraged ASCII is out Unicode is in.
    // Also watch out for [[dict objectForKey:@"cocoa"]cString] notice the
    // lack of a space between the receiver and the message.
    // And lastly since this is a Cocoa example why not use an NSLog()
    NSLog(@"entry for cocoa: %@", [dict objectForKey:@"cocoa"]);

    enumerator = [dict keyEnumerator];
    
    while ((key = [enumerator nextObject])) {
        //printf("%s : %s\n", [key cString],
        //        [[dict objectForKey: key] cString]);
        NSLog(@"%@ : %@", key, [dict objectForKey:key]);
    }
    
   [pool release];

    return 0;//NSApplicationMain(argc, argv);
}