2013-10-11 106 views
2

以下方法被調用,以便在AFNetworking從我的應用服務器獲取信息後填充我的Core-DataNSPrivateQueueConcurrencyType未正確保存

該信息似乎完美地工作,因爲當表更新時,我可以看到UITableView中正在更新的新信息。

現在我的問題是,即使我可以看到信息(從服務器提取後,存儲到核心數據並重新顯示在我的UITableView中顯示)如果我然後關閉我的應用程序並重新打開它,信息就不存在了。

看起來好像信息不是持久性的,問題似乎是線程。因爲如果我刪除我的方法中的線程選項一切正常。

我在想什麼?我嘗試了大部分我碰到過的東西,但似乎找不到解決方案。

NSManagedObjectContext *childContext = [[NSManagedObjectContext alloc] 
             initWithConcurrencyType:NSPrivateQueueConcurrencyType]; 
childContext.parentContext = managedObjectContext; 
myModel.context = childContext; 


    [childContext performBlock:^{ 
// ... Lots Controller logic code that then calls the class myModel where all my Core-Data save methods are 

    // Sort Wall Pictures 
        if ([dataHolder[@"verb"] isEqualToString:@"addWallPicture"]) { 
         data = @{ @"resourceID":dataHolder[@"_id"][@"$id"], 
            @"resourceName":dataHolder[@"details"][@"resourceName"], 
            @"author":@{ @"id":dataHolder[@"userId"][@"$id"], 
               @"username":dataHolder[@"details"][@"authorName"] }, 
            @"likesNumber":@0, 
            @"likesPeople":@[] 
            }; 

         [myModel saveSocialWall:data date:date verb:dataHolder[@"verb"] code:dataHolder[@"_id"][@"$id"] myUser:myUser]; 
         continue; 
        } 
[childContext save:&error]; 
}]; 
+0

你保存的主要方面以及?保存子上下文僅保存到主上下文,並將主上下文保存到存儲文件。 –

+0

如何在線程完成後保存主要上下文? –

回答

10

您還必須在某些時刻保存主要上下文,例如,保存子上下文後。

保存子上下文僅保存到主上下文,並將主上下文保存到存儲文件。

像這樣(寫在手機上,會有 是語法錯誤):

// ... 
[childContext save:&error]; 
[mainContext performBlock:^{ 
    [mainContext save:&error]; 
}]; 

雨燕2.0,這將是:

do { 
    try childContext.save() 
    mainContext.performBlock { 
     do { 
      try mainContext.save() 
     } catch let err as NSError { 
      print("Could not save main context: \(err.localizedDescription)") 
     } 
    } 
} catch let err as NSError { 
    print("Could not save private context: \(err.localizedDescription)") 
} 
+0

如何忽略childContext所做的更改。因爲如果我不想保存childContext並對Core Data執行一些其他操作並保存在mainContext上,那麼以前的childContext也會被保存嗎? – Vacca

+0

@Vacca:保存* child *上下文將其更改合併到父項(主要上下文)中。將* main *上下文保存到持久性存儲區(如果它沒有另一個父級),但不會修改子上下文。 –

+0

不,我是說如果我保存我的子上下文時不保存我的RootParentContext(主),由於某些情況我必須忽略這些更改。之後,在下一跳保存時,如果某些操作嘗試保存在根(主)上,以前的子上下文更改是否會保存或忽略? – Vacca