Is there NSMutableDictionary literal syntax to remove an element?

半腔热情 提交于 2019-12-08 21:18:01

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!