I'm using Magical Record to facilitate Core Data operations. Imagine we have a set of json like this, and a Core Data model defined exactly the same:
{
"cars": [
{
"name": "Corolla",
"brand": {
"name": "Toyota"
},
"price": 20000
},
{
"name": "Pirus",
"brand": {
"name": "Toyota"
},
"price": 50000
},
{
"name": "RAV-4",
"brand": {
"name": "Toyota"
},
"price": 30000
},
{
"name": "Golf",
"brand": {
"name": "VW"
},
"price": 40000
},
{
"name": "Polo",
"brand": {
"name": "VW"
},
"price": 20000
}
]
}
Now, if we use Magical Record helper method:
- (BOOL) MR_importValuesForKeysWithObject:(id)objectData;
or
+ (id) MR_importFromObject:(id)data;
it will be imported as 5 entries of Car and 5 entries of Brand.
However, in our Core Data model, Car-Brand relationship is a many-to-many one, and Brand's name attribute is supposed to be unique, so I'm expecting 5 entries of Car and 2 entries of Brand (Toyota and VW).
My question is how to maintain the data uniqueness while importing with Core Data. Is this something I can define in Core Data model, like unique attribute? or is it I need to override Magical Record's import method?
You need to tell MagicalRecord what is the unique identifier. In your case you have no unique ID, but you could probably use the name
attribute.
Assuming you have a Car
NSManagedObject with a relationship to a Brand
NSManagedObject, you have to set relatedByAttribute
to name
on the relationship to the Brand
in the user info dictionary.
Once you have done this MagicalRecord will look up any records with the attribute name
and use the appropriate record if one already exists, or create one if needed.
This means you won't have to override important with a category class.
Let me know if you need additional information.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With