views:

3481

answers:

3

HashTables/HashMaps are one of the most (if not the most) useful of data-structures in existence. As such, one of the first things I investigated when starting to learn programming in Cocoa was how to create, populate, and read data from a hashtable.

To my surprise: all the documentation I've been reading on Cocoa/Objective-C programming doesn't seem to explain this much at all. As a Java developer that uses "java.util" as if it were a bodily function: I am utterly baffled by this.

So, if someone could provide me with a primer for creating, populating, and reading the contents of a hashtable: I would greatly appreciate it.

+21  A: 

NSDictionary and NSMutableDictionary?

And here's a simple example:

NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
[dictionary setObject:anObj forKey:@"foo"];
[dictionary objectForKey:@"foo"];
[dictionary removeObjectForKey:@"foo"];
[dictionary release];
Martin Gordon
Note that, in true object-oriented fashion, the Cocoa classes are named for "what they do" rather than "how they're implemented" as HashTable, HashMap, and friends are in Java, C#, and so on.
Chris Hanson
C# calls it a Dictionary as well!
bobobobo
+6  A: 

If you're using Leopard (and Cocoa's new Garbage Collection), you also want to take a look at NSMapTable.

Barry Wark
Cool, I'll check that out ... thanks.
Ryan Delucchi
+2  A: 

In addition to NSDictionary, also check out NSSet for when you need a collection with no order and no duplicates.

Chris Hanson