Magical Record not saving

淺唱寂寞╮ 提交于 2019-12-03 14:21:41

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]

Have you tried using the saveInBackgroundWithBlock: utility method?

If not you might want to try something like the code below. Note that it'll save all your objects in one go in the background and then perform the completion block on the main thread:

[MagicalRecord saveInBackgroundWithBlock:^(NSManagedObjectContext *localContext){
    Service *service = [Service createInContext:localContext];

    ... set values ...
} completion:^{
    ...
}];

Other than that, you can see if [[NSManagedObjectContext defaultContext] hasChanges] returns YES to check if it's an issue with the saving or the entity itself.

In my swift project I do:

MagicalRecord.setupCoreDataStack()

So then I need to do the following to save to disk:

NSManagedObjectContext.MR_defaultContext().MR_saveToPersistentStoreAndWait()

move the line

[[NSManagedObjectContext defaultContext] saveNestedContexts];

outside the for loop , it worked for me

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!