Key Value Coding - setValue:forKey: where value is NULL

4.2k Views Asked by At

I am reading documentation that says setValue:forKey: will treat a NULL value as if it is being removed. Yet, I have an example such as the following that is consistently crashing:

[myObj setValue:[aDictionary valueForKey:@"keyDoesNotExist"] forKey:@"anotherKey"];

This line of code crashes if aDictionary does not contain the key keyDoesNotExist. Is there any way around that? What's the appropriate thing to do here?

myObj is an instance of NSManagedObject. "anotherKey" is a one to many relationship where myObj can contain many of "anotherKey".

1

There are 1 best solutions below

5
On BEST ANSWER

When you call setValue:forKey: with a nil value, the method -setNilValueForKey: is called. By default (in NSObject's implementation), this raises an invalid argument exception. You can do something else with a nil value by overriding -setNilValueForKey: and doing whatever you'd like.

Alternatively, if you call myObj's anotherKey setter directly, you shouldn't get an exception (dependent on the implementation of setAnotherKey: of course):

myObj.anotherKey = [aDictionary valueForKey:@"keyDoesNotExist"]; 

The documentation you're reading is probably for NSMutableDictionary. NSMutableDictionary's implementation of setValue:forKey: calls removeObjectForKey: if the value is nil. That's not true for NSObject subclasses, which I'm presuming is what myObj is.

This behavior is discussed in the NSKeyValueCoding Protocol Reference documentation.