Is there an NSMutableDictionary literal syntax for deleting an element?

There is literal syntax for adding an object and modifying an object in NSMutableDictionary, is there literal syntax for deleting an object?

+6
source share
3 answers

Yes, but ... :-)

This is not supported by default, but the new syntax for setting dictionary items uses the setObject:forKeyedSubscript: method, and not setObject:forKey: Thus, you can write a category that replaces the former, and either installs or removes the item:

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

Add this to your application and then:

 dict[aKey] = nil; 

will delete the item.

+5
source

No. No. I tried to find a link to the proof, but failed :)

+3
source

Starting with iOS 9 and macOS 10.11, these are two equivalents:

  [dictionary removeObjectForKey:@"key"]; dictionary[@"key"] = nil; 

See Foundation Release Notes (find the NSMutableDictionary subscript syntax change header).

+1
source

All Articles