Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there NSMutableDictionary literal syntax to remove an element?

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

like image 255
Boon Avatar asked Feb 26 '14 20:02

Boon


People also ask

Can you create a mutable array and mutable Dictionary using literal syntax?

Just like with NSString s, collection objects made via literal arrays and dictionaries are immutable. You cannot create mutable collections with the literal syntax, so you will have to make a mutable copy after making the immutable dictionary or array.

What is NSDictionary?

An object representing a static collection of key-value pairs, for use instead of a Dictionary constant in cases that require reference semantics.

What is a literal Objective c?

In Objective-C, any character, numeric or boolean literal prefixed with the '@' character will evaluate to a pointer to an NSNumber object initialized with that value. C's type suffixes may be used to control the size of numeric literals.


2 Answers

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.

like image 154
CRD Avatar answered Oct 03 '22 04:10

CRD


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

like image 45
Avt Avatar answered Oct 03 '22 06:10

Avt