HashTables in Cocoa

后端 未结 5 1631
日久生厌
日久生厌 2020-12-24 12:16

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

相关标签:
5条回答
  • 2020-12-24 12:49

    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];
    
    0 讨论(0)
  • 2020-12-24 12:49

    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]);
    
    0 讨论(0)
  • 2020-12-24 12:55

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

    0 讨论(0)
  • 2020-12-24 13:09

    You can try using an NSHashTable!

    0 讨论(0)
  • 2020-12-24 13:10

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

    0 讨论(0)
提交回复
热议问题