There is a literal syntax to add object and change object in an NSMutableDictionary, is there a literal syntax to remove object?
Is there NSMutableDictionary literal syntax to remove an element?
Asked Answered
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.
<insert warning about clobbering framework methods with categories> Wish it had been written this way in the first place! –
Tattan
@JoshCaswell - Wondered who might raise that. Officially Apple don't encourage this, but use it themselves to replace methods... What must be avoided is replacing the same method using different categories, then all bets are off as to which method gets called; but until Apple stop the practice themselves this should work fine. You can set the environment variable
OBJC_PRINT_REPLACED_METHODS
to YES
to see all the methods that are replaced in this way (in Xcode set it in the scheme). –
Perdition Excellent question and answer! –
Rennin
No. There is not. I have tried to find proof link but did not succeed :)
You can link the LLVM page that lists all the literals. –
Gleiwitz
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
).
© 2022 - 2024 — McMap. All rights reserved.
nil
?dict[aKey] = nil;
– TattansetObject:forKeyedSubscript:
to remove if the object isnil
. – Tattan