Avoid duplicate records when importing data using Magical Record

I use Magical Record to facilitate master data operations. Imagine we have such a json suite, and the Core Data model is 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 the Magical Record helper method:

 - (BOOL) MR_importValuesForKeysWithObject:(id)objectData; 

or

 + (id) MR_importFromObject:(id)data; 

It will be imported as 5 records in Car and 5 records Brand.

However, in our Core Data model, Car-Brand relationships are many-to-many, and the Brand name attribute must be unique, so I expect 5 Car entries and 2 Brand entries (Toyota and VW).

My question is how to preserve the uniqueness of data when importing using Core Data. Is this something I can define in the Core Data model, for example, a unique attribute? or do I need to override the Magical Record import method?

+7
source share
1 answer

You need to tell MagicalRecord what is a unique identifier. In your case, you do not have a unique identifier, but you can probably use the name attribute.

Assuming you have a Car NSManagedObject with a relation to the Brand NSManagedObject, you should set relatedByAttribute to name in relation to Brand in the user information dictionary.

After you have done this, MagicalRecord will search for any records with the name attribute and use the corresponding record if it already exists, or create it if necessary.

This means that you do not have to redefine important categories with the class.

Let me know if you need more information.

+6
source

All Articles