Search code examples
core-dataios7github-mantle

Mantle and Core Data - update instead of delete/create


Is there a way in mantle to update an existing record in core data instead of always create new ones? This blog post looks promising, but I don't find the method updateWithJSON: somewhere in Mantle. Right now, I'm doing the following:

MantleObject *mantleObject = [MTLJSONAdapter modelOfClass:[MantleObject class] fromJSONDictionary:dictionary error:NULL];
CoreDataObject *coreDataObject = [CoreDataObject MR_findFirstByAttribute:@"primaryKey" withValue:mantleObject.primaryKey];

// avoid duplicates
if (coreDataObject != nil) {
    [coreDataObject MR_deleteEntity];
}

[MTLManagedObjectAdapter managedObjectFromModel:mantleObject insertingIntoContext:[NSManagedObjectContext MR_contextForCurrentThread] error:NULL];

It works as expected, but I don't like the idea of always deleting and creating the 'same' object over and over again. So I would love to have the opportunity of updating existing objects (overwriting is fine; ALL the values of the new object can replace the existing ones).


Solution

  • Mantle has supported updating managed objects since version 1.3.

    Your model classes need to implement the MTLManagedObjectSerializing protocol method propertyKeysForManagedObjectUniquing and return the property keys which identify a model, which in your case appears to primaryKey:

    + (NSSet *)propertyKeysForManagedObjectUniquing {
        return [NSSet setWithObject:@"primaryKey"];
    }
    

    The header doc explains how it works, but basically the MTLManagedObjectAdapter will fetch an existing managed object if one exists and update that object rather than create a new one.

    I would recommend using Mantle's built in support, rather than trying to find duplicates yourself. This will result in simpler, more maintainable code.