我正在使用Stanford的CoreDataTableViewController来显示动态表。
应用程序的工作原理:要向此表添加行,将弹出子屏幕以进行数据输入,当子屏幕关闭时,将插入新创建的managedObject,并且回调会重新加载表。
我注意到重新进入屏幕后,表中间歇性地丢失了新添加的行。我注意到只有在第一次使用saveToURL创建UIManagedDocument对象时才会出现此行为。随后,在重新启动应用程序并使用openWithCompletionHandler打开UIManagedDocument后,列表始终显示正确。
这是我用来创建/打开UIManagedDocument的代码:
- (void)performWithDocument:(OnDocumentReady)onDocumentReady
{
void (^OnDocumentDidLoad)(BOOL) = ^(BOOL success)
{
NSLog(@"Called OnDocumentDidLoad");
onDocumentReady(self.document);
};
if (![[NSFileManager defaultManager] fileExistsAtPath:[self.document.fileURL path]])
{
[self.document saveToURL:self.document.fileURL
forSaveOperation:UIDocumentSaveForCreating
completionHandler:OnDocumentDidLoad];
}
else if (self.document.documentState == UIDocumentStateClosed)
{
NSLog(@"Calling openWithCompletionHandler:OnDocumentDidLoad");
[self.document openWithCompletionHandler:OnDocumentDidLoad];
}
else if (self.document.documentState == UIDocumentStateNormal)
{
OnDocumentDidLoad(YES);
}
}
运行上面的代码时,总是调用onDocumentDidLoad(),并且成功标志为YES。
任何帮助都将非常感激。提前谢谢!
- 编辑以下代码以显示我创建的方法,然后关闭并重新打开文档以响应Jody - 我仍然遇到了同样的问题。 ---
- (void)performWithDocument:(OnDocumentReady)onDocumentReady
{
void (^OnDocumentDidLoad)(BOOL) = ^(BOOL success)
{
NSLog(@"Called OnDocumentDidLoad success: %d", success);
onDocumentReady(self.document);
};
void (^OnDocumentDidClose)(BOOL) = ^(BOOL success)
{
NSLog(@"Called OnDocumentDidClose, openWithCompletionHandler success: %d", success);
[self.document openWithCompletionHandler:OnDocumentDidLoad];
};
void (^OnDocumentDidSave)(BOOL) = ^(BOOL success)
{
NSLog(@"Called OnDocumentDidSave success: %d", success);
if (self.document.documentState == UIDocumentStateClosed)
{
NSLog(@"Calling openWithCompletionHandler:OnDocumentDidLoad from onDocumentDidSave - was closed");
[self.document openWithCompletionHandler:OnDocumentDidLoad];
}
else if (self.document.documentState == UIDocumentStateNormal)
{
// TODO Close and reopen?
NSLog(@"Calling closeWithCompletionHandler:OnDocumentDidClose from onDocumentDidSave - was normal");
[self.document closeWithCompletionHandler:OnDocumentDidClose];
}
};
if (![[NSFileManager defaultManager] fileExistsAtPath:[self.document.fileURL path]])
{
// Database doesn't exist, create it, then close and reopen in completion handler
[self.document saveToURL:self.document.fileURL
forSaveOperation:UIDocumentSaveForCreating
completionHandler:OnDocumentDidSave];
}
else if (self.document.documentState == UIDocumentStateClosed)
{
// Open existing database
NSLog(@"Calling openWithCompletionHandler:OnDocumentDidLoad");
[self.document openWithCompletionHandler:OnDocumentDidLoad];
}
else if (self.document.documentState == UIDocumentStateNormal)
{
// Already opened
OnDocumentDidLoad(YES);
}
}
答案 0 :(得分:0)
您没有说明您使用的iOS版本,这几乎总是很重要。
创建文档时存在iOS 5问题。很久以前,我在创建UIManagedDocument
时使用了以下内容。它仍然在我的库代码中,因为我从来没有足够的动力来花时间来查看问题是否得到解决。
如果文档不存在,请将其保存以进行创建,并在完成处理程序中将其关闭,然后在该完成处理程序中将其打开。这样,除非它已经存在,否则我从未真正使用过文档。