7

我正在使用 UIManagedDocument 来管理我的数据。我创建模型并使用它,一切似乎都在工作,但我的更改并没有被写回 SQLite 存储。

UIManagedDocument 的文档说自动保存应该负责将数据持久化到数据库中,但这似乎没有发生。

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

这会获取我想要添加的对象(并成功)。

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

这会将项目添加到另一个对象的项目集合中,然后告诉文档我已完成更改。

我预计在此之后不久会看到写入核心数据存储的更改,但是在 Instruments 中观察,我发现它永远不会发生。

items 集合是一个 NSOrderedSet,并且由于对此项目的评论:

NSOrderedSet 生成的访问器中抛出的异常

我添加了一个 addItemsObject: 到包含集合的对象:

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

也许 Core Data 被告知项目集合已更改出现问题,但我不知道如何。

4

3 回答 3

10

我发现了我的问题。原来我试图添加的对象有错误——我错过了一个必需的属性——并且没有覆盖 handleError 没有迹象表明有问题。

在这里写博客:http: //blog.stevex.net/2011/12/uimanageddocument-autosave-troubleshooting/

于 2012-08-21T00:03:38.143 回答
1

在我从服务器获取数据的方法中,我首先创建实体,然后调用这两个方法来立即保存对文档的更改:

[self.document updateChangeCount:UIDocumentChangeDone];
[self.document savePresentedItemChangesWithCompletionHandler:^(NSError *errorOrNil) {
            ...
        }];
于 2013-11-26T10:19:33.583 回答
1

来自@stevex 链接的主要内容/摘要:

确保调用 UIManagedDocument 的-updateChangeCount方法或触发向文档的undoManager. 否则文档认为它不需要保存任何东西。

此外,对一些关键方法进行子类化将允许您查看自动保存何时发生以及是否存在错误。

- (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);
}
于 2017-10-23T21:33:06.760 回答