Objective C - Core Data relationship
i've a problem with Core Data relationship. I pass to my method addData an array of data. It is an array of dictionary. Every dictionary have 3 keys, "A", "B", "C". Key C store another array of dictionary that have 3 keys. The first array is of item Type and the second of item Subtype. Now, how can i place it into CoreData?The entity name is "Type" and "Subtype". And how can i take it from CoreData? Th开发者_运维技巧anks
You need an entity for Type
which will have attributes a
and b
and a relationship c
(lower case to conform with naming conventions). c
is a 1 to many relationship to the Subtype
entity. The Subtype entity has three attributes, one for each of the dictionary's keys and a relationship type
which is the inverse relationship for the Type
object's c
.
Use the following pseudocode (I can't be bothered with the detail of setting up core data. You can easily read the docs) to help you create a solution to populate your model from the original array of dictionaries.
for (NSDictionary* aType in typeArray)
{
// Create a managed object for the dictionary called aTypeManagedObject
[aTypeManagedObject setValue: [aType objectForKey: @"A"] forKey: @"a"];
[aTypeManagedObject setValue: [aType objectForKey: @"B"] forKey: @"b"];
for (NSDictionary* subType in [aType objectForKey: @"C"])
{
// Create a managed object for the dictionary called aSubtypeManagedObject
// set the attributes in the same way as a and b above
[aSubTypeManagedObject setValue: aType forKey: @"type"]; // Automatically updates the aType's c relationship
}
}
// Save all the changes
Next time you fetch the Type managed object from the core data store, all that will be set up already.
[aTypeManagedObject valueForKey: @"c"]
will return an array of the subtype objects for that Type object.
精彩评论