【问题标题】:Notifications when NSOperation finishes?NSOperation 完成时的通知?
【发布时间】:2015-05-16 21:12:07
【问题描述】:

Stack Overflow 上的其他问题和答案谈到观察 operations.count,添加“完成操作” 等等

GCD finishedHow do I know all my tasks in Grand Central Dispatch finished?

NSOperationQueue finishes operations

KVO for monitoring all tasks finished

是否有我可以订阅的通知发送已完成的操作?

【问题讨论】:

  • 您想知道一个操作何时完成或整个操作队列何时完成?
  • 好的,没问题!有两种常用的方法,我在回答中都提供了。

标签: objective-c nsoperation


【解决方案1】:

最简单的方法就是让您的 NSOperation 的main 在其末尾发布一个 NSNotification。因此,其他任何人都可以注册该通知并得知操作已结束(并且可以返回 NSOperation 以获取存储在可能需要的属性中的任何数据)。

这是一个典型的结构:

- (void) main {
    if ([self isCancelled])
        return;
    // ... all the action goes here ...
    if (![self isCancelled])
        [[NSNotificationCenter defaultCenter] 
         postNotificationName:@"OperationFinished" object:self];
}

请注意,您不应该对 NSNotification 到达的线程做出任何假设

另一种方法是在 NSOperation 的 isFinished 上使用 KVO,但这可能会变得很麻烦,我不确定我是否会建议这样做。

【讨论】:

  • 啊,所以您使用的是自定义 NSOperation 类?
  • 是的,但这并不重要。但是,如果您正在执行 NSBlockOperation,则只需使用 KVO 解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多