Search code examples
objective-csyntaxobjective-c-category

Subscripting syntax for NSMapTable in iOS 6


I'm using NSMapTable in a number of places in an iOS 6 project, and would like to be able to use the new dictionary subscripting style for accessing objects. (NSMapTable behaves mostly like an NSMutableDictionary, but can be configured with various memory management options for the keys and values it stores. More background in this StackOverflow question.)

The compiler reports this when attempting to use subscripting syntax on an NSMapTable instance:

Expected method to read dictionary element not found on object of type 'NSMapTable *'.

How can I use a category to extend NSMapTable to allow the new NSDictionary-style subscripting?


Solution

  • The answer's actually simple; see this question for more information about how subscripting is implemented. Add a category like this.

    Header:

    @interface NSMapTable (Subscripting)
    
    - (void)setObject:(id)obj forKeyedSubscript:(id <NSCopying>)key;
    - (id)objectForKeyedSubscript:(id)key;
    
    @end
    

    Implementation:

    @implementation NSMapTable (Subscripting)
    
    - (void)setObject:(id)obj forKeyedSubscript:(id <NSCopying>)key {
        [self setObject:obj forKey:key];
    }
    
    - (id)objectForKeyedSubscript:(id)key {
        return [self objectForKey:key];
    }
    
    @end
    

    This makes me wonder, for a moment, whether subscript access is actually a tiny bit slower than the alternative in some or all cases, but the words "premature optimization" make that thought inconsequential.