I have a NSMutableDictionary
.
NSMutableDictionary * dict = @{
@"0" : @"car",
@"1" : @"ball",
@"2" : @"plane",
}
At one point, by error, I was assigning a nil to to an element on a dictionary. For example:
dict[@"1"] = nil;
for my surprise, instead of crash, the element "1" is being deleted.
Is this something recent? a sanctioned feature or a bug? I wonder if this is a feature, because I always used something like
[dict removeObjectForKey:@"1"];
To remove objects from dictionaries.
I never knew it was possible. Perhaps Apple is making Objective-C similar to Swift.
I just verified the behavior in Swift 2.0.
var dict: NSMutableDictionary = [ "0" : "car", "1" : "ball", "2" : "plane" ];
dict["1"] = nil
print("\(dict)")
It must to be a bug because it contradicts the documentation.
From NSMutableDictionary Class Reference:
- setObject:forKeyedSubscript: Adds a given key-value pair to the dictionary.
Declaration
OBJECTIVE-C
- (void)setObject:(ObjectType)object
forKeyedSubscript:(id)aKeyParameters
objectThe value for aKey. A strong reference to the object is maintained by the dictionary.
IMPORTANTRaises an NSInvalidArgumentException if anObject is nil. If you need to represent a nil value in the dictionary, use NSNull.
aKeyThe key for value. The key is copied (using copyWithZone:; keys must conform to the NSCopying protocol). If aKey already exists in the dictionary, anObject takes its place.
IMPORTANTRaises an NSInvalidArgumentException if aKey is nil.
UPDATE: 2016-04-21
Apple has updated it's documentation! passing a nil
value can be used to delete a key.
objectThe value for aKey. A strong reference to the object is maintained by the dictionary.
Passing nil will cause any object corresponding to aKey to be removed from the dictionary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With