6

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

user2864740
  • 60,010
  • 15
  • 145
  • 220
Boon
  • 40,656
  • 60
  • 209
  • 315
  • 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;` – jscs Feb 26 '14 at 20:44
  • 1
    @JoshCaswell Storing nil to dictionary will cause a crash. – Boon Feb 26 '14 at 20:48
  • That's what I figured. It's too bad they didn't write `setObject:forKeyedSubscript:` to remove if the object is `nil`. – jscs Feb 26 '14 at 22:07

3 Answers3

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.

CRD
  • 52,522
  • 5
  • 70
  • 86
  • 1
    Wish it had been written this way in the first place! – jscs Feb 26 '14 at 22:08
  • 1
    @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). – CRD Feb 26 '14 at 22:20
  • Excellent question and answer! – Christian Gossain Jan 27 '16 at 22:53
3

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

Avt
  • 16,927
  • 4
  • 52
  • 72
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).

Patrick Beard
  • 592
  • 6
  • 11