This is another “mostly reading” chapter, but there are several methods that are meant to go in Grokking Recipes. There is enough to cover that this will be a two-post chapter.
Section 4.1: NSManagedObject
NSManagedObject is the class for Core Data objects, which are the basis for the individual items like recipes, ingredients or recipe types in Grokking Recipes. They can be created without coding in a .xcdatamodel, or subclassed to add functionality beyond that provided by NSManagedObject.
First up is the @dynamic keyword, which is something like the opposite of @synthesize: it tells the compiler not to create accessor methods, and that they will be provided at runtime, by KVC (Key-Value Coding).
Accessing the parts of Core Data objects is the next part of section 4.1. The most straight forward way is via the methods -valueForKey: or -setValue:forKey. If it’s necessary to access the value without setting off notifications, use the method -setPrimitiveValue:forKey, after using -willChangeValueForKey:. When it’s time to allow the notification of the change to go out, use -didChangeValueForKey:. It should go something like
[self willChangeValueForKey:@"name"]; // save old value for use in undo [self setPrimitiveValue:theNewValue ForKey:@"name"]; // change to new value // do the stuff needed before sending out the notification [self didChangeValueForKey:@"name"];
Accessing to-many relationships is different than accessing properties or to-one relationships. Since these relationships are unordered, they are accessed by an NSSet (for reading) or an NSMutableSet acquired from the -mutableSetValueForKey: method. You can then simply mutate that set, and that will change the relationships.
The last part of the section covers sub-classing NSManagedObject, mostly discussing which methods can be over-ridden and which ones shouldn’t. The list of methods that a developer can safely override is short: -awakeFromInsert, -awakeFromFetch, willTurnIntoFault and didTurnIntoFault. Faulting is discussed in chapter 6, Performance Tuning. Faulting has to do with objects that have been removed from RAM (or never loaded) and stored on disk to reduce the application’s memory footprint.