Search code examples
objective-cnsmutabledictionaryobjective-c-literals

Is there NSMutableDictionary literal syntax to remove an element?


There is a literal syntax to add object and change object in an NSMutableDictionary, is there a literal syntax to remove object?


Solution

  • Yes, but... :-)

    This is not supported by default, however the new syntax for setting dictionary elements uses the method setObject:forKeyedSubscript: rather than setObject:forKey:. So you can write a category which replaces the former and either sets or removes the element:

    @implementation NSMutableDictionary (RemoveWithNil)
    
    - (void) setObject:(id)obj forKeyedSubscript:(id<NSCopying>)key
    {
       if (obj)
          [self setObject:obj forKey:key];
       else
          [self removeObjectForKey:key];
    }
    
    @end
    

    Add that to your application and then:

    dict[aKey] = nil;
    

    will remove an element.