Database Reference
In-Depth Information
- ( void )importData:(NSDictionary*)values //CSV translated into a dictionary
{
[self willChangeValueForKey:@ "name" ];
[self willChangeValueForKey:@ "desc" ];
[self willChangeValueForKey:@ "serves" ];
[self willChangeValueForKey:@ "type" ];
[self setPrimitiveValue:[values valueForKey:@ "name" ] forKey:@ "name" ];
[self setPrimitiveValue:[values valueForKey:@ "desc" ] forKey:@ "desc" ];
[self setPrimitiveValue:[values valueForKey:@ "serves" ] forKey:@ "serves" ];
[self setPrimitiveValue:[values valueForKey:@ "type" ] forKey:@ "type" ];
[self didChangeValueForKey:@ "type" ];
[self didChangeValueForKey:@ "serves" ];
[self didChangeValueForKey:@ "desc" ];
[self didChangeValueForKey:@ "name" ];
}
In this example code, we are handling all the change notifications ourselves
and setting the values into our NSManagedObject directly using the -setPrimitiveVal-
ue:forKey: method. This will cause all the values to be updated prior to the
notifications being fired.
Accessing Relationships
Accessing relationships on an NSManagedObject is nearly as easy as accessing
attributes. There is a bit of a difference between working with a to-one rela-
tionship and a to-many relationship, though.
Accessing a To-One Relationship
When we are accessing a to-one relationship, we can treat it the same as we
do an attribute. Since Core Data is first and foremost an object graph, a to-
one relationship can be treated exactly like a property that contains any
other object. For example, the relationship between RecipeIngredient and its Recipe
is a to-one relationship from the RecipeIngredient side. Therefore, if we were
accessing this relationship from that point of view, the code would be as
follows:
NSManagedObject *ingredient = ...;
NSManagedObject *recipe = [ingredient valueForKey:@ "recipe" ];
In this example, we are using the -valueForKey: KVC method to access the rela-
tionship, and the NSManagedObject returns the object on the other side of the
relationship, which is the entity. Likewise, to set the recipe for an ingredient,
we would use the following code:
NSManagedObject *ingredient = ...;
NSManagedObject *recipe = ...;
[ingredient setValue:recipe forKey:@ "recipe" ];
 
 
Search WWH ::




Custom Search