我在Core Data上使用Justin Driscoll's article,使用单例模式的UIManagedDocument为UITabViewController设置它。我在模拟器上运行应用程序。它第一次正常工作。数据库创建成功,我可以在tableview控制器中查看每个选项卡的数据。但是,当我重新启动应用程序时,应用程序崩溃并出现错误
Assertion failure in -[UIManagedDocument openWithCompletionHandler:],
** Terminating app due to uncaught exception 'NSInternalInconsistencyException',
reason: 'attempt to open or a revert document that already has an open or revert
operation in flight
导致崩溃的代码。我使用NSLog语句进行了一些调试。
if (![[NSFileManager defaultManager] fileExistsAtPath:[self.document.fileURL path]]) {
NSLog(@"document doesnot exist and hence START CREATING");
[self dataIntoDocument:self.document];
NSLog(@"document Finished Creating");
[self.document saveToURL:self.document.fileURL forSaveOperation:UIDocumentSaveForCreating completionHandler:OnDocumentDidLoad];
NSLog(@"Saved to URL on disk");
} else if (self.document.documentState == UIDocumentStateClosed) {
NSLog(@"document is closed and its needs to be opened");
[self.document openWithCompletionHandler:OnDocumentDidLoad];
} else if (self.document.documentState == UIDocumentStateNormal) {
NSLog(@"test document is in normal state");
OnDocumentDidLoad(YES);
}
从第一次运行结果当数据库不存在时
2013-08-12 14:51:35.458 <My APP>[368:11603] document doesnot exist and hence its created Start
2013-08-12 14:51:38.716 <My APP>[368:11603] document doesnot exist and hence its Finished Creating
2013-08-12 14:51:38.718 <My APP>[368:11603] NSManagedContext did save.
2013-08-12 14:51:38.718 <My APP>[368:11603] Saved to URL on disk
2013-08-12 14:51:38.721 <My APP>[368:11603] document is closed and its needs to be opened
2013-08-12 14:51:38.772 <My APP>[368:11603] NSManagedObjects did change
从第二次运行结果:当数据库存在于URL
时2013-08-12 14:53:43.758 <MY APP> [380:11603] document is closed and its needs to be opened
2013-08-12 14:53:43.761 <MY APP>[380:11603] document is closed and its needs to be opened
2013-08-12 14:53:43.762
我理解它失败的原因,因为它不应该连续开启。我在所有视图控制器中都有相同的代码,它们控制选项卡以获取UIManagedDocument的实例。请让我知道我错过了什么。谢谢
-(id) initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if (!self.databaseDocument) {
[[LTDatabaseDocumentHandler sharedDatabaseDocumentHandler] performWithDocument:^ (UIManagedDocument *document) {
self.databaseDocument = document;
[self populateTableViewArrayFromDocument:self.databaseDocument];
}];
}
return self;
}
答案 0 :(得分:0)
我想。我需要使用 - (void)viewWillAppear:动画方法来实例化UIManagedDocument的共享实例而不是 - (id)initWithCoder。因为只有当用户尝试查看选项卡时才会执行viewWillAppear方法。
答案 1 :(得分:0)
我不明白这对你有什么帮助,但至少你明白了。它似乎就像viewWillAppear:可能不是初始化这类东西的最佳位置。