A typical custom accessor method could be written as the following:
- (NSString *)name
{
[self willAccessValueForKey:@"name"];
NSString *myName = [self primitiveName];
[self didAccessValueForKey:@"name"];
return myName;
}
- (void)setName:(NSString *)newName
{
[self willChangeValueForKey:@"name"];
[self setPrimitiveName:newName];
[self didChangeValueForKey:@"name"];
}
It’s clear the meaning of setPrimitiveName. It allows you to access the “raw ” variable without KVC (preventing a run loop inside the accessor) and set the value passed in. The same observation can be applied to the getter.
From the documentation it’s clear that setPrimitiveName disables change notifications methods: willChangeValueForKey and counterpart.
Now my question is the following: why do you need to wrap that method inside willChangeValueForKey: and didChangeValueForKey: methods?
Reading the Core Data programming there is written that:
NSManagedObject disables automatic key-value observing (KVO) change
notifications for modeled properties, and the primitive accessor
methods do not invoke the access and change notification methods. For
unmodeled properties, on Mac OS X v10.4 Core Data also disables
automatic KVO; on Mac OS X v10.5 and later, Core Data adopts to
NSObject’s behavior.
Why do I need to inform that I’m ready to access a key (accessor or instance variable) and then I’ve done with it? Who is informed?
Hope my question is clear. Thank you in advance.
You need it to inform the view,that your value has changed.
Let’ take for example, that you would use MKMapView and put some annotations on it, taking coordinates from Core Data, and then, somehow, you change it’s location.
If you getter/setter didn’t post these notifications, MKMapView wouldn’t know of these changes in locations, and wouldn’t move it to the new one.
You can also track the date of creation/change of your objects with these notifications.
I guess, that redo/undo is also made by this.
NOTE
I would like to know, if Core Data uses these notifications somehow under the hood. Does anybody has any ideas on this subject?