使用最新版Magical Record保存NSManagedContext的正确方法

Apo*_*llo 5 cocoa-touch ios magicalrecord

为了保存我当前的NSManagedObjectContext使用[localContext MR_saveNestedContexts];但我得到一个警告,该方法已被弃用.

我应该如何保存NSManagedObjectContext最新版本的魔法记录(今天从GitHub中提取,2013年7月19日).

Jef*_*gan 5

查看他们的文档.
https://github.com/magicalpanda/MagicalRecord/blob/master/Docs/Saving-Entities.md

而且,当我过去问他们问题时,他们反响敏捷.你也可以随时尝试一下.

编辑:

不知道为什么我得到了投票.也许文档太混乱了.尝试使用

- (void) MR_saveToPersistentStoreWithCompletion:(MRSaveCompletionHandler)completion;
Run Code Online (Sandbox Code Playgroud)

我没有使用最新版本的MagicalRecord,但我认为这应该是正确的

    //get the context for the current thread
    //this context can be updated by anyone other process on this thread that uses the same MR_contextForCurrentThread call
    //it's a local store that can be merged to a parent store
    NSManagedObjectContext *localContext = [NSManagedObjectContext MR_contextForCurrentThread];

    //create an NSManagedObject of type YourEntity and insert it into the localContext object
    NSManagedObject *obj = [YourEntity MR_createInContext:localContext];

    //make any updates to obj

    //save the localContext async
    //this call should save all nested NSManagedObjectContexts as well (if they exist)
    [localContext  MR_saveToPersistentStoreWithCompletion:^{
        //when the async save is complete, this block gets executed
        //blocks work very similarly to javascript callbacks
        //basically it's a function reference or block of code that get's packaged up and can be passed around
        //In this case, the completion block allows to to run any code after the save has been completed.
    }];
Run Code Online (Sandbox Code Playgroud)

我开始时没有意识到的一件事是当我创建我的实体时,它也将它插入到上下文中.它导致我不小心保存了我不需要保留的对象.为了避免这种情况,我设置了一个子上下文,只在我想要保留对象时保存它.

self.context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
self.context.parentContext = [NSManagedObjectContext MR_defaultContext];
Run Code Online (Sandbox Code Playgroud)

  • 仅供参考 - 投票支持不是我,但这个答案_did_出现在10k用户的标志队列中,可能是因为仅链接答案在StackOverflow上不被认为是好事.始终包含足够的信息,以便在链接中断时,您的答案仍然有用.有关详细信息,请参阅[此处](http://meta.stackexchange.com/q/8231/164376). (3认同)