Magical Record not saving

Kermit the Frog picture Kermit the Frog · Dec 7, 2012 · Viewed 7.7k times · Source

I am using Magical Record: https://github.com/magicalpanda/MagicalRecord

I am trying to save records that I get the from my website to the sqllite database using Magical Record and Core Data, but I keep getting the error:

MR_saveWithErrorCallback:](0xaaa6bd0) NO CHANGES IN CONTEXT <NSManagedObjectContext (0xaaa6bd0): *** BACKGROUND SAVING (ROOT) ***> on *** BACKGROUND THREAD *** - NOT SAVING

Here is the code:

             for(int i = 0; i < count; i += 1)
             {
                 // results  = array of all services from site
                 NSDictionary * result = [results objectAtIndex: i];

                 NSNumber * sid = @([[result objectForKey: @"id"] intValue]);
                 NSNumber * parent = @([[result objectForKey: @"parent"] intValue]);
                 Service * service  = [Service createEntity];

                 NSString * image = [NSString stringWithFormat: @"%@", [result objectForKey: @"image"]];

                 NSString * name  = [NSString stringWithFormat: @"%@", [result objectForKey: @"name"]];
                 NSString * machine_name  = [NSString stringWithFormat: @"%@", [result objectForKey: @"machine_name"]];


                 [service setDate: [NSDate date]];
                 [service setSid: sid];
                 [service setName: name];

                 [service setImage: image];
                 [service setParent: parent];
                 [service setMachine_name: machine_name];


                 [[NSManagedObjectContext defaultContext] saveNestedContexts];

Answer

Edward Huynh picture Edward Huynh · Dec 18, 2012

The issue is that you are not saving the right context. If you look at the source, [Service createEntity] creates the ManagedObject in the context for the current thread. Not in the defaultContext.

So what you need to do is, instead of [[NSManagedObjectContext defaultContext] saveNestedContexts], you should be saving the context for the current thread (i.e the context which the ManagedObject was created in). So the code should be [[NSManagedObjectContext MR_contextForCurrentThread]