iOS: Why can't I set nil to NSDictionary value?

后端 未结 5 1436
清酒与你
清酒与你 2020-12-29 01:15

This might be very basic question but I was wondering why can\'t I assign nil as NSDictionary value? I have following statement many places in my code. If [q objectFor

5条回答
  •  悲&欢浪女
    2020-12-29 02:01

    You can set a nil value using setValue:forKey but it removes the key.

    If you want to be able to set a key to nil you could use setValue:forKey: which will remove the key if you set it to nil (quote from documentation below). Note the Value instead of Object.

    setValue:forKey:

    Adds a given key-value pair to the dictionary.

    ...
    
    Discussion

    This method adds value and key to the dictionary using setObject:forKey:, unless value is nil in which case the method instead attempts to remove key using removeObjectForKey:.

    When you later try and get the object using objectForKey: for the key that you removed by setting it to nil you will get nil back (quote from documentation below).

    Return value:

    The value associated with aKey, or nil if no value is associated with aKey.

    Note: The key will not actually be present in the dictionary so it won't be obtained using allKeys; or be enumerated over.

提交回复
热议问题