Is it still true that it's a bad idea to name attributes and relationships like any non-parameter method of NSObject or NSManagedObject?
I did some 开发者_Python百科little experimentation on this.
I created an boolean attribute, named isFault. You know, that's a method of NSManagedObject and therefore actually not allowed for an attribute name because of KVC.
Simply, I used the default Core Data template for this test, but created the data model programmatically so I can show you what I do.
So here we go:
NSAttributeDescription *badAttr = [[NSAttributeDescription alloc] init];
[badAttr setName:@"isFault"];
[badAttr setAttributeType:NSBooleanAttributeType];
[badAttr setOptional:YES];
// don't want to occupy you with the whole, non-important rest ...
Next, I've modified the -insertNewObject method of the controller, added these lines:
// Assume: An managed object is created into the context, but not saved yet...
NSLog(@"isFault = %d", [newManagedObject isFault]); // 0 = NO
BOOL isFault = [[newManagedObject valueForKey:@"isFault"] boolValue];
NSLog(@"isFault = %d", isFault); // 0 = NO
[newManagedObject setValue:[NSNumber numberWithBool:YES] forKey:@"isFault"];
isFault = [[newManagedObject valueForKey:@"isFault"] boolValue];
NSLog(@"isFault = %d", isFault); // 0 = NO
Like you can see, I'm not able to set the isFault attribute to YES. It remains NO. Now, changing the attribute name to isFaultXYZ, will allow that.
So actually, what I wanted to ask is... since this stuff seems to depend on KVC, does the rule only apply to methods that return something and have no parameter? And does it matter what data type is returned? For example, -changedValues has no parameter and returns an NSDictionary. But since there is no attribute type like that, would this cause a collision anyways?
So, here is the evidence. When naming the attribute changedValues, THIS happens after attempting to access it via KVC:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSCFDictionary boolValue]: unrecognized selector sent to instance 0x1205680'
2010-06-10 14:52:40.232 CoreData[33996:207] Stack: (
8035,
4437,
8825,
精彩评论