iOS 7完成处理程序永远不会被调用

在下面的代码中,没有一个完成处理程序被执行。 我能find的一个解释是iPhone Simulator 5.1中的这个Bug,使用UIManagedDocument的Xcode 4.5 。 它说这可能是iPhone模拟器5.1中的一个错误。 不过,我试过iPhone模拟器6.0,6.1和7.0,他们都没有工作。 我会很感激你的帮助。

(顺便说一下,我在斯坦福iOS课程中看到了这个代码,第14讲)

NSURL *url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]; url = [url URLByAppendingPathComponent:@"DataDocument"]; UIManagedDocument *document = [[UIManagedDocument alloc] initWithFileURL:url]; if(![[NSFileManager defaultManager] fileExistsAtPath:[url path]]){ NSLog(@"This logs"); [document saveToURL:url forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success){ NSLog(@"This never logs"); }]; }else if(document.documentState == UIDocumentStateClosed){ NSLog(@"This logs"); [document openWithCompletionHandler:^(BOOL success){ NSLog(@"This never logs"); }]; }else{ //I have a separate log for this, but it's never 'else' } 

编辑:我发现一个问题似乎是处理完全相同的问题。 我不能得到一个nsmanageobjectcontext我只是把它钉在完成处理程序不被执行。

编辑:我发现问题是什么:因为openWithCompletionHandlerasynchronous执行,我的应用程序会尝试在打开之前使用文档。 使用运行循环解决了这个问题。 下面的例子。

 if(doc.documentState == UIDocumentStateClosed){ NSLog(@"This logs"); __block BOOL waitingOnCompletionHandler = YES; [doc openWithCompletionHandler:^(BOOL success){ NSLog(@"This logs too!"); }]; while (waitingOnCompletionHandler) { NSDate *futureTime = [NSDate dateWithTimeIntervalSinceNow:0.1]; [[NSRunLoop currentRunLoop] runUntilDate:futureTime]; } }