Is there NSMutableDictionary literal syntax to remove an element?
Asked Answered
H

3

6

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

Horvath answered 26/2, 2014 at 20:30 Comment(3)
I haven't tried it (away from a compiler at the moment), but what happens if you try to set a value to nil? dict[aKey] = nil;Tattan
@JoshCaswell Storing nil to dictionary will cause a crash.Horvath
That's what I figured. It's too bad they didn't write setObject:forKeyedSubscript: to remove if the object is nil.Tattan
P
5

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.

Perdition answered 26/2, 2014 at 21:25 Comment(3)
<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
S
3

No. There is not. I have tried to find proof link but did not succeed :)

Swordtail answered 26/2, 2014 at 20:34 Comment(1)
You can link the LLVM page that lists all the literals.Gleiwitz
U
2

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).

Unsatisfactory answered 19/9, 2017 at 17:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.