0
votes

I'm using Coredata and MagicalRecord in an iOS project, but I can't figure out some saving problems. I've one ManagedObjectContext to keep my object in memory in order to display some information. When I want to create a new entity, I create it in a background context with this following method :

__block B *b = [B MR_createInContext:[[DataBaseManager sharedManager] managedObjectContext]];
[a setB:b];
__block A *aInLocalContext;
[MagicalRecord saveWithBlock:^(NSManagedObjectContext *localContext) {
    B *bInLocalContext = (B *)[b MR_inContext:localContext];
    aInLocalContext = (A *)[a MR_inContext:localContext];
    [aInLocalContext setB: bInLocalContext];
} completion:^(BOOL success, NSError *error) {}];

b is created in my displaying context, but bInLocalContext is nil in the backgroundContext(i.e localContext), so my data is not persisted and the relationship is not set. Is it the right way to create and save new NSManagedObjectContext in a background context and keep the data in the displaying context in order to update the UI ?

Thanks in advance

1

1 Answers

0
votes

I know this is an older question, but you never save the context after you create b. Thus, when you call

[b MR_inContext:localContext],

it returns nil because b was never persisted.

As to your question about the right way to save and display, yes that will work but without knowing how you have set up [[DataBaseManager sharedManager] managedObjectContext], you need to make sure that it knows about changes made in other contexts, either by refreshing from the persistent store or by observing NSManagedObjectContextDidSaveNotification.

It's worth mentioning that since you are using MagicalRecord you should probably just use MR_defaultContext, as that is what it is there for!