[ACCEPTED]-iOS: Why can't I set nil to NSDictionary value?-null

Accepted answer
Score: 71

It wants an actual object... use NSNull

[NSNull null];

0

Score: 51

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 12 could use setValue:forKey: which will remove the key if 11 you set it to nil (quote from documentation 10 below). Note the Value instead of Object.

setValue:forKey:

Adds 9 a given key-value pair to the dictionary.

...
Discussion

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

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

Return value:

The value associated with aKey, or 1 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.

Score: 5

You can set nil object in this way:

NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];

dictionary[@“key”] = nil;

Have 1 you noticed it?

NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];

/* this statement is safe to execute    */

dictionary[@“key”] = nil;

/* but this statement will crash application    */

[dictionary setObject:nil forKey:@"key"];
Score: 1

When using this method:

func setObject(_ anObject: Any, forKey aKey: NSCopying)

Parameters (according to Apple doc's):

anObject:

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

aKey

Raises 2 an invalidArgumentException if aKey is 1 nil.

Score: 0

My friend using nil as marker is a sign 6 of bad programming . nil is reserved for 5 some diffrent purpose .

if([q objectForKey:@"text"] != nil)
    [dict setObject:[q objectForKey:@"text"] forKey:@"text"];
else
    [dict removeObjectforKey:@"text"]; // this will do nothing if key does not exsist.

//by default for 4 all the keys the value is nil and you are 3 trying to override this behavior. going 2 against the language rules will always get 1 you in trouble .

to check just use

if([dict objectforKey:@"text"] !=nil){} // this will work becuase default value is nil 
itself 

More Related questions