Search code examples
iphoneobjective-ciosmagicalrecordmknetworkkit

Magic Record Threaded Saves


I can't quite figure out the correct way to do this. I am having trouble persisting the object I create in the block.

[op addCompletionHandler:^(MKNetworkOperation *completedOperation) {

            User *u = [User MR_createEntity];
            u.name = @"bob";
            [[NSManagedObjectContext MR_contextForCurrentThread] MR_save];

    } errorHandler:^(MKNetworkOperation *completedOperation, NSError *error) {
    }];

Cant quite seem to get bob persist when I reopen the app. Can someone explain what is happening? I think that u is created in a new context? and then this is not merged with the main context?


Solution

  • You can force u to be created in the same context as the context you're trying to save, and then save with u's context.

    User *u = [User MR_createInContext:[NSManagedObjectContext MR_contextForCurrentThread]];
    u.name = @"bob";
    [[u managedObjectContext] MR_saveToPersistentStoreAndWait];