我有一个NSInvocationOperation可以在后台下载和解析一系列的NSXMLDocuments以使我的UI保持响应。我尝试停止Invocation操作是调用我的NSOperationQueue的cancellAllOperations方法。但似乎这并不能停止Invocation的执行。您对如何解决这个问题有什么想法吗?
更新: 当我这样做时,Instruments显示出有很多内存泄漏。 请谨慎操作! 我会把这里保留下来,以防我真的发现了什么,其他人可以想办法解决内存泄漏问题。
这是一个扭曲的想法,我正在打字时重新尝试:
将操作设置为NSInvocationOperation的initWithTarget:selector:object:方法中的对象。 假设你已经有了一个NSOperationQueue(我们称之为queue):
NSInvocationOperation *operation = [NSInvocationOperation alloc];
operation = [operation initWithTarget:self selector:@selector(myOperation:) object:operation];
[queue addOperation:operation];
[operation release];
请注意,我们必须将alloc()方法拆分为单独的调用。否则,我们无法将设置为! - (void)myOperation:(id)object {
NSInvocationOperation *operation = (NSInvocationOperation *)object;
if ([operation isCancelled]) return;
...
}
在initWithTarget:...调用中,确保您的选择器以冒号结尾,因为现在您将传递一个对象。
到目前为止,还不错。现在如果我可以强制执行cancelAllOperations,我就知道这是否有效了。 :)
您需要检查NSInvocationOperation是否已取消。
要在NSInvocationOperation中执行此操作,可以使用键值观察:
在运行操作时将对象添加为NSInvocationOperation的isCancelled观察者:
NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:<targetObj> selector:@selector(<targetMethod>) object:nil];
[operation addObserver:<targetObj> forKeyPath:@"isCancelled" options:NSKeyValueObservingOptionNew context:nil];
[operQueue addOperation:operation];
[operation release];
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context;
你的NSOperation
对象的实现需要在收到取消通知时停止正在执行的任务,清理并退出。发送取消所有操作的消息将导致队列停止出队新的操作并向当前正在运行的任何操作发送取消消息。
在你的操作主方法中,应该检查isCancelled
并在被取消时处理该状态。
有关更多信息,请参见线程编程指南中的创建和管理操作对象。
NSInvocationOperation
时,您不能以标准方式检查isCancelled
。 - jrdioko