Search code examples
iosobjective-ccore-datamagicalrecord

Is there a way to save NSManagedObjects 1 at a time


I'm facing this problem where I have an NSMutableArray containing NSManagedObjects.

And I want to iterate each one NSManagedObject, set a value to a variable and then save them.

The problem is that I have a verification to see if the objects are in Database or not, and after I save my first NSManagedObject to the database all the others NSManagedObjects that are in that array are also inserted into the database...

Here's a piece of code that describes what is my issue:

for (Category* c in categories) {
    Category* original = [Database getCategoryByID:c.categoryid];
    // After the first save this will have value because it saves all the objects
    // that are in categories Array and the version will be the same...
    
    if (original != nil && original.version >= c.version) {
        // This object is already up to date so do not make any changes
    } else {
        // This object is not up to date, or it does not exist
        // update it's contents
        c.name = name;
        
        [[c managedObjectContext] MR_saveToPersistentStoreAndWait]; 
        // Here it saves all the objects instead of only 1 object
    }
}

Is there a way to only save 1 object at a time while having other NSManagedObjects inside an NSMutableArray ?


Solution

  • With Core Data, you tell a context to save, and it saves everything it has. There's no way to save just one object unless that object is the only one in a context with changes.

    In your case, it looks like your array of Category objects are managed objects and that they belong to a managed object context. The easiest way to avoid unexpected saving is to move the save command until after the loop. When you reach that point,

    • Any Category that needed to be created or updated is ready to save
    • Any Category that didn't need to be updated has no changes, so it won't be affected by saving the context.

    So it should be safe to save everything in the context then. If it has changes, it gets updated, and if it doesn't, it won't change.