Ryan Delucchi
Ryan Delucchi

Reputation: 7748

HashTables in Cocoa

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.

Upvotes: 28

Views: 34423

Answers (5)

Barry Wark
Barry Wark

Reputation: 107774

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

Upvotes: 8

Martin Gordon
Martin Gordon

Reputation: 36399

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];

Upvotes: 59

mylittleswift
mylittleswift

Reputation: 320

Use NSHashTable from iOS 6.0+ SDK. The hash table is modeled after NSSet with the following differences: It can hold weak references to its members. Its members may be copied on input or may use pointer identity for equality and hashing. It can contain arbitrary pointers (its members are not constrained to being objects).

 NSHashTable *hashTable = [NSHashTable 
 hashTableWithOptions:NSPointerFunctionsCopyIn];
 [hashTable addObject:@"foo"];
 [hashTable addObject:@"bar"];
 [hashTable addObject:@100];
 [hashTable removeObject:@"bar"];
 NSLog(@"Members: %@", [hashTable allObjects]);

Use NSMapTable from iOS 6.0+ SDK. The map table is modeled after NSDictionary with the following differences: Keys and/or values are optionally held “weakly” such that entries are removed when one of the objects is reclaimed. Its keys or values may be copied on input or may use pointer identity for equality and hashing. It can contain arbitrary pointers (its contents are not constrained to being objects).

 id delegate = ...;
 NSMapTable *mapTable = [NSMapTable 
 mapTableWithKeyOptions:NSMapTableStrongMemory
                                         valueOptions:NSMapTableWeakMemory];
 [mapTable setObject:delegate forKey:@"foo"];
 NSLog(@"Keys: %@", [[mapTable keyEnumerator] allObjects]);

Upvotes: 3

Julius Guzy
Julius Guzy

Reputation: 121

You can try using an NSHashTable!

Upvotes: 12

Chris Hanson
Chris Hanson

Reputation: 55194

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

Upvotes: 7

Related Questions