iosiphonensmutabledictionary

Assigning nil to an element on NSMutableDictionary in Objective-C removes that element, is that a sanctioned feature or bug?


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.


Solution

  • 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)aKey

    Parameters

    object

    The value for aKey. A strong reference to the object is maintained by the dictionary.

    IMPORTANT

    Raises an NSInvalidArgumentException if anObject is nil. If you need to represent a nil value in the dictionary, use NSNull.

    aKey

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

    IMPORTANT

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

    object

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