Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid duplicated entries when importing data with Magical Record

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?

like image 747
Chris Chen Avatar asked Dec 29 '12 20:12

Chris Chen


1 Answers

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.

like image 100
runmad Avatar answered Oct 24 '22 04:10

runmad