Iterating through NSDictionary

Iteration through NSDictionary could be achieved at least in two ways: using NSArray with [NSDictionary allKeys] or NSEnumerator.
Snippets:

	NSArray *keyArray =  [bigUglyDictionary allKeys];
	int count = [keyArray count];
	for (int i=0; i < count; i++) {
		NSDictionary *tmp = [bigUglyDictionary objectForKey:[ keyArray objectAtIndex:i]];
	}
	NSEnumerator *enumerator = [bigUglyDictionary keyEnumerator];
	id key;
	while ((key = [enumerator nextObject])) {
		NSDictionary *tmp = [bigUglyDictionary objectForKey:key];
	}

Second way is a little bit faster, so if you work with huge dictionaries and have no need of array with their keys – use it.

Tags: , ,

5 responses

  1. Riddhiman
    Posted September 28, 2010 at 18:09 | Permalink

    thanks, very helpful

  2. Posted January 19, 2011 at 02:11 | Permalink

    Or:


    for( NSString *aKey in [bigUglyDictionary allKeys] )
    {
    // do something
    }

    Or somewhat faster:


    for( NSString *aKey in bigUglyDictionary )
    {
    // do something
    }

    Or better yet, if your target OS supports blocks:

    [bigUglyDictionary enumerateKeysAndObjectsUsingBlock: ^(id key, id obj, BOOL *stop) {
    // do something with key and obj
    }];

  3. Posted April 4, 2011 at 21:39 | Permalink

    you have got an ideal blog here! would you wish to make some invite posts on my weblog?

  4. Posted September 27, 2012 at 03:56 | Permalink

    Thanks (also Alan), that piece of code was very helpful.

  5. Ambuj Shukla
    Posted January 12, 2013 at 11:40 | Permalink

    Sir I’m using NSString* name = (NSString *)ABRecordCopyCompositeName(person);
    to store contacts name from iphone contacts and I want that in an array so that it stores in array[0],array[1] and soon so that I can match it with some other array. Can u plz explain it to me.

Leave a Reply