How to get good grip on NSMutableDictionary, NSEnumerator, NSMutableSet?

1.1k views Asked by At

I am little bit backward in knowledge on these three topics: NSMutableDictionary, NSEnumerator, NSMutableSet. When I want to use them, it feels very hard, even when I've gone through the developer documentation.

Is there any sample code to understand it clearly for all three topics?

Please help me.

Thank you, Madan Mohan.

1

There are 1 answers

4
Jonathan Sterling On BEST ANSWER

The best way to understand these depends on what your prior experience is. NSDictionary is exactly what it sounds like: a dictionary. What that means is that given a key (or a headword, as in a dictionary), you can look up a value (or definition):

For instance, this dictionary gives information about my dog:

KEY        VALUE
-------------------------------------------
@"name"       @"tucker"
@"species"    @"canis lupus familiaris"
@"favorite"   @"biscuits"

With a dictionary dogInfo containing that information, we could send [dogInfo objectForKey:@"name"] and expect to receive @"tucker".

The difference between NSDictionary and NSMutableDictionary is that the latter allows changes after initialization. This lets you do things like [dogInfo setObject:@"fetch" forKey:@"game"]. This is helpful for maintaining state, memoizing referentially transparent requests, etc.

NSSet is a way to have a bunch of objects, with a few important bits: there is no defined order to those objects, and there can only be one of each object (no duplicates). Use NSSet for when you need to contain unique, unordered objects. NSMutableSet is the variant of NSSet which allows for changes (such as adding or removing objects) after initialization.

NSEnumerator is a bit more complicated, but you usually won't need to deal with it unless you are writing your own libraries, are coding archaically, or are doing complex enumerations. Subclasses of NSEnumerator are used by collection classes, such as NSDictionary, NSArray, and NSSet, to allow their objects to be enumerated. Usually, you'd just enumerate over them using a foreach-loop, since they all implement <NSFastEnumeration>. But sometimes, you'll want to do more specific things, like enumerate over the objects (instead of the keys) of a dictionary, or enumerate over an array in reverse. This is where instances of NSEnumerator (usually defined as properties on your collection objects) will become helpful.

Update

Justin in the comments pointed out that NSEnumerator conforms to <NSFastEnumeration>; that means, the chances are next-to-nothing that you'll need to know how to use an NSEnumerator; you can just do a foreach loop over the enumerator itself, like so:

for (id object in [dogDict objectEnumerator]) {
  // doing something with the object, disregarding its key
}