2013-07-19 85 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