【发布时间】:2013-04-23 07:56:55
【问题描述】:
我正在使用斯坦福大学的 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);
}
}
【问题讨论】:
标签: core-data uimanageddocument