Re: NSNull vs nil in NSManagedObject setValue: v forKey: k
Re: NSNull vs nil in NSManagedObject setValue: v forKey: k
- Subject: Re: NSNull vs nil in NSManagedObject setValue: v forKey: k
- From: Ben Trumbull <email@hidden>
- Date: Mon, 1 Mar 2010 09:38:04 -0800
>> NSManagedObject* obj; // gets created somehow
>>
>> [obj setValue: nil forKey: @"bar"]; // succeeds where NSDictionary fails
>> [obj setValue: [NSNull null] forKey: @"bar"]; // fails where NSDictionary succeeds
>>
>> so - this is conceptually buggy thinking and the thoughtful developer could be forgiven for being VERY SURPRISED by this behavior that is NOT DOCUMENTED.
A review of <http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSNull_Class/Reference/Reference.html> clearly documents the behavior. Additional inferences beyond the documentation are unsupported. "The NSNull class defines a singleton object used to represent null values in collection objects (which don’t allow nil values)" None of the examples involve KVC. There are no references to KVC in the related documentation. NSNull isn't a Key Value Coding thing, this is an NSArray, NSSet, NSDictionary thing. Nothing in the documentation implies otherwise.
Secondly, NSDictionary is untyped. NSNull is valid for any key. NSManagedObject properties have an explicit type. Values are expected to conform to the type specified for the property named by the key. NSNull is not an NSString. Your attempts otherwise are a basic violation of OOP.
Thirdly, nil and NSNull are both valid values for typed NSManagedObject properties but they are not for NSDictionary. In an NSDictionary, NSNull and nil must be equivalent because there are no other legal possibilities. nil is never a valid value. But for either transformable or transient NSManagedObject properties, both NSNull and nil are legal values. Should we make it illegal to have optional properties that use NSNull ?
In general, NSManagedObject does not perform value type coercion. We chose this to balance several design criteria including detection of developer error (e.g. masking bad values), performance, and convenience (doing this yourself is trivial). If enough developers feel another balancing would be more productive, we'd be happy to reevaluate that. You should contribute by filing bugs.
- Ben
p.s. On an ancillary note, gratuitous use of NSNull outside of collections gets tedious & problematic. Since NSNull != nil, all the client code then has to check multiple conditions, which this is easily forgotten, and then selector not recognized bugs crash apps because NSNull isn't the right class.
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden