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: , ,

3 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?

Leave a Reply