问题
There is a literal syntax to add object and change object in an NSMutableDictionary, is there a literal syntax to remove object?
回答1:
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.
回答2:
No. There is not. I have tried to find proof link but did not succeed :)
回答3:
As of iOS 9 and macOS 10.11, these two are equivalent:
[dictionary removeObjectForKey:@"key"];
dictionary[@"key"] = nil;
See the Foundation release notes (search for the heading NSMutableDictionary subscript syntax change
).
来源:https://stackoverflow.com/questions/22052577/is-there-nsmutabledictionary-literal-syntax-to-remove-an-element