【发布时间】:2011-10-18 10:19:27
【问题描述】:
我正在尝试在后台解析一些 XML 文件,以便 UI 不会冻结。我必须检查两件事:
- NSOperationQueue 完成了吗?
- NSOperation - 解析失败了吗?
我有一个继承 NSOperation 的类,如果解析失败,则会调用一个委托。队列中的操作仅限于同时进行一项。
我的问题是我不能依赖在我得到队列完成消息之前执行失败消息的事实。有时我在收到完成的消息之前没有收到失败的消息。然后,例如,我有这个命令:
操作 1 成功 操作 2 成功 操作队列完成 操作 3 失败
所有消息都发送到主线程。在我收到完成的消息后,我想继续我的代码,但前提是所有操作都成功。如何处理队列完成后调用委托消息的问题。
这是我的代码的一些部分:
//XMLOperation.m
- (void)main {
NSLog(@"Operation started");
if ([self parseXML]) {
[self performSelectorOnMainThread:@selector(finishedXMLParsing) withObject:nil waitUntilDone:NO];
} else {
[self performSelectorOnMainThread:@selector(failedXMLParsing) withObject:nil waitUntilDone:NO];
}
}
NSLog(@"Operation finished");
}
//StartController.m
[self.xmlParseQueue addObserver:self forKeyPath:@"operations" options:0 context:NULL];
...
- (void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object
change:(NSDictionary *)change context:(void *)context
{
if (object == self.xmlParseQueue && [keyPath isEqualToString:@"operations"]) {
if ([self.xmlParseQueue.operations count] == 0) {
// Do something here when your queue has completed
NSLog(@"queue has completed");
}
}
else {
[super observeValueForKeyPath:keyPath ofObject:object
change:change context:context];
}
}
【问题讨论】:
-
截至 2017 年 1 月,Apple 文档提到您可以访问 "operationCount" 。只需在需要时检查。 developer.apple.com/reference/foundation/…
标签: objective-c multithreading nsoperation nsoperationqueue