2013-07-19 31 views

回答

5

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

而且,当我问他们在过去的问题,他们已经非常敏感。你也可以随时尝试你的手。

编辑:

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

- (void) MR_saveToPersistentStoreWithCompletion:(MRSaveCompletionHandler)completion; 

我不使用最新版本的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. 
    }]; 

一件事,当我开始是当我建立了我的实体哪知它也将其插入到上下文中。它使我无意中保存了我不需要坚持的对象。为了避免这种情况,我设置了一个子上下文,只有当我想保存这些对象时才保存它。

self.context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType]; 
self.context.parentContext = [NSManagedObjectContext MR_defaultContext]; 
+0

不知道为什么你得到了downvote要么,这不是我(只是upvoted否定)。你介意提供一行代码来实现你提到的方法吗?我仍然获得Objective-C的所有语法,但并不真正理解withCompletion:^(BOOL成功,NSError *错误)完成],当您键入此方法时自动完成... – Apollo

+3

仅供参考 - 它不是我向下投票,但这个答案_did_出现在10k用户的标志队列中,这可能是因为仅链接答案在StackOverflow上不被视为一件好事。始终包含足够的信息,以便在链接断开时,您的答案仍然有用。有关更多信息,请参见[这里](http://meta.stackexchange.com/q/8231/164376)。 – joran

+1

MR_contextForCurrentThread已弃用 – Gargo