iOS5.1:同步任务(等待完成)

问题描述:

我有一个同步openWithCompletionHandler:(UIManagedDocument)与主要活动的基本问题。iOS5.1:同步任务(等待完成)

情况: 我有一个管理共享UIManagedDocument的单例类。此类提供了一种方法,该方法应该以正常状态(即创建或打开它,无论什么是必需的)传递文档。 但是因为openWithCompletionHandler:在后台异步执行它的主要工作,所以我的程序应该等待设置fetchedResultsController,直到文档真正打开。当数据库没有准备好时,“viewWillAppear”方法(当前)不会产生有用的输出。 等待会对我好,但得到通知可能是更好的方法。也许viewWillAppear结果不是正确的点setupFetchedResultsController,因为没有在runloop调用。

有没有一个标准模式来实现这一目标?

更多的背景(不是我认为如此重要) 我正在研究一个涉及CoreData UIManagedDocument的小型iOS 5.1应用程序。 我喜欢去年秋天在iTunes-U上的斯坦福大学课程第14课的例子。一切工作正常,直到我试图将UIManagedDocument的处理从UITableViewController类转换为处理我的文档的单独类。 在原始版本中,FetchedResultsController在完成处理程序中设置。

我建议以下Justin Driscoll的优秀帖子Core Data with a Single Shared UIManagedDocument

您将在UIManagedDocument单例中找到完整的文章,并在performWithDocument上找到示例。您的fetchedResultsController设置代码应该放在performWithDocument:^ {}块中。

另请注意,openWithCompletionHandler不是线程安全的 - 在打开文档时同时调用performWithDocument会导致崩溃。对我来说这个解决方案不是微不足道的(而且非常适用于特定应用),所以如果遇到同样的问题,我建议您查看UIDocumentStateChangedNotification,它可以通知文档状态更改,并且可以作为多个文档开启者的同步点。

一些片段,如果你有兴趣,

首先在MYDocumentHandler的初始化,设置在最后一个额外的通知:

[[NSNotificationCenter defaultCenter] addObserver:self 
              selector:@selector(documentStateDidChange:) 
               name:UIDocumentStateChangedNotification 
               object:self.document]; 

然后在performWithDocument,@synchronized(self.document)在关键的开放/创建节以确保一次只有一个线程进入,并阻止进一步的线程,直到打开/创建成功。

最后添加以下功能:

- (void)documentStateDidChange:(NSNotification *)notification 
{ 
    if (self.document.documentState == UIDocumentStateNormal) 
     @synchronized (self.document) { 
      ... unblock other document openers ... 
     } 
} 

至于块/解锁线程,因人而异。我使用dispatch_semaphore_t以及一些dispatch_queues来满足应用程序特定的需求。你的情况可能像等待完成或放弃其他线程一样简单。