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.
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:
With a dictionary
dogInfo
containing that information, we could send[dogInfo objectForKey:@"name"]
and expect to receive@"tucker"
.The difference between
NSDictionary
andNSMutableDictionary
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). UseNSSet
for when you need to contain unique, unordered objects.NSMutableSet
is the variant ofNSSet
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 ofNSEnumerator
are used by collection classes, such asNSDictionary
,NSArray
, andNSSet
, to allow their objects to be enumerated. Usually, you'd just enumerate over them using aforeach
-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 ofNSEnumerator
(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 anNSEnumerator
; you can just do aforeach
loop over the enumerator itself, like so: