HashTables in Cocoa

2020-02-17 09:11发布

问题:

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.

回答1:

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


回答2:

You can try using an NSHashTable!



回答3:

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



回答4:

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



回答5:

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