2011-12-03 55 views
7

我正在使用UIManagedDocument來管理我的數據。我創建模型並使用它,並且一切似乎都正常,但我的更改沒有寫回到SQLite存儲區。UIManagedDocument沒有保存

UIManagedDocument的文檔說,自動保存應該照顧到數據持久化到數據庫,但似乎並沒有發生。

NSManagedObjectContext *moc = [doc managedObjectContext]; 
    NSError *error = nil; 
    MyItem *itemToAdd = (MyItems *)[moc existingObjectWithID:(NSManagedObjectID *)itemsID error:&error]; 

這會提取我想添加的對象(併成功)。

[itemContainer addItemsObject:itemToAdd]; 
    [doc updateChangeCount:UIDocumentChangeDone]; 

這將項目添加到另一個對象中的項目集合,然後告訴文檔我完成了更改。

我希望在這之後的一段時間內看到寫入核心數據存儲區的改變,但在Instruments看來,我發現它永遠不會發生。

的項目回收是一個NSOrderedSet,因爲對這個項目的意見:保存集合對象:

- (void)addItemsObject:(MyItem *)value 
{ 
    NSMutableOrderedSet* tempSet = [NSMutableOrderedSet orderedSetWithOrderedSet:self.items]; 
    [tempSet addObject:value]; 
    self.items = tempSet; 
} 

Exception thrown in NSOrderedSet generated accessors

我已經添加了一個addItemsObject核心數據被告知項目集合已經改變,但是我不知道如何做。

+0

隨着儀器,我可以看到數據正在寫入核心數據緩存。但它並未顯示在Core Data Saves工具中,如果我殺了並重新啓動應用程序,我的更改就消失了。 – stevex

+3

我發現我的問題。事實證明,我在嘗試添加對象時遇到錯誤 - 我錯過了一個必需的屬性 - 並且沒有重寫handleError,沒有任何跡象表明存在問題。在這裏博客:http://blog.stevex.net/2011/12/uimanageddocument-autosave-troubleshooting/ – stevex

回答

9

我發現我的問題。事實證明,我在嘗試添加對象時遇到錯誤 - 我錯過了一個必需的屬性 - 並且沒有重寫handleError,沒有任何跡象表明存在問題。

在博客在這裏: http://blog.stevex.net/2011/12/uimanageddocument-autosave-troubleshooting/

+1

這是一個了不起的發現 - CoreData在很多情況下會允許對象被保存在內存中,但不是保存到磁盤有時會導致*非常*誤導,並且您提供的修復功能非常好。 – NSTJ

+0

我提出了一個答案,總結您的鏈接,以防萬一未來的鏈接失敗:) – olynoise

1

在我的方法,我從服務器獲取數據,我首先創建實體之後,我調用這兩個方法來保存更改立即文檔:

從@ stevex的鏈接
[self.document updateChangeCount:UIDocumentChangeDone]; 
[self.document savePresentedItemChangesWithCompletionHandler:^(NSError *errorOrNil) { 
      ... 
     }]; 
0

主要採取跳投/摘要:

請確保調用UIManagedDocument的-updateChangeCount方法或觸發與文檔的登記變更。否則,文檔不認爲需要保存任何內容。

另外,子類化一些關鍵方法將允許您查看何時發生自動保存以及是否有錯誤。

- (id)contentsForType:(NSString *)typeName error:(NSError * _Nullable __autoreleasing *)outError { 

    id retVal = [super contentsForType:typeName error:outError]; 
    NSLog(@"Autosaving document. contentsForType at fileURL %@ error %@", self.fileURL, *outError); 
    return retVal; 
} 


- (void)handleError:(NSError *)error userInteractionPermitted:(BOOL)userInteractionPermitted { 
    [super handleError:error userInteractionPermitted:userInteractionPermitted]; 
    NSLog(@"ManagedDocument handleError: %@ %@", error.localizedDescription, error.userInfo); 
}