0

我正在使用Justin Driscoll在 Core Data 上的文章 with UIManagedDocument in singleton pattern 为 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;
 }
4

2 回答 2

0

我估计。我需要使用 -(void)viewWillAppear:animated 方法来实例化 UIManagedDocument 的共享实例,而不是 -(id)initWithCoder。因为 viewWillAppear 方法仅在用户尝试查看选项卡时才会执行。

于 2013-08-12T23:55:40.797 回答
0

我不明白这对你有什么帮助,但至少你明白了。看起来 viewWillAppear: 可能不是初始化这类东西的最佳位置。

于 2013-09-06T02:50:34.817 回答