如何停止一个NSInvocationOperation?

9
我有一个NSInvocationOperation可以在后台下载和解析一系列的NSXMLDocuments以使我的UI保持响应。我尝试停止Invocation操作是调用我的NSOperationQueue的cancellAllOperations方法。但似乎这并不能停止Invocation的执行。您对如何解决这个问题有什么想法吗?
4个回答

11

更新: 当我这样做时,Instruments显示出有很多内存泄漏。 请谨慎操作! 我会把这里保留下来,以防我真的发现了什么,其他人可以想办法解决内存泄漏问题。

这是一个扭曲的想法,我正在打字时重新尝试:

将操作设置为NSInvocationOperationinitWithTarget:selector:object:方法中的对象。 假设你已经有了一个NSOperationQueue(我们称之为queue):

NSInvocationOperation *operation = [NSInvocationOperation alloc];
operation = [operation initWithTarget:self selector:@selector(myOperation:) object:operation];
[queue addOperation:operation];
[operation release];
请注意,我们必须将alloc()方法拆分为单独的调用。否则,我们无法将设置为!
然后,在您的operation()方法中,将对象强制转换回来,并根据需要添加检查。例如:
  - (void)myOperation:(id)object {
    NSInvocationOperation *operation = (NSInvocationOperation *)object;
    if ([operation isCancelled]) return;
    ...
  }

initWithTarget:...调用中,确保您的选择器以冒号结尾,因为现在您将传递一个对象。

到目前为止,还不错。现在如果我可以强制执行cancelAllOperations,我就知道这是否有效了。 :)


不会尝试它,因为有泄漏。但是这个想法很棒! - Mike Keskinov

8

您需要检查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;

要注意的是,NSOperationQueue的cancellAllOperations可能会改变isCancelled的值。在这里可以设置一个私有标志,targetMethod可以检查它并在必要时进行取消。

5
以上帖子很棒,但更直接回答原始问题的是:似乎你无法停止NSInvocationOperation对象,因为它不支持取消。你需要继承它。

3

你的NSOperation对象的实现需要在收到取消通知时停止正在执行的任务,清理并退出。发送取消所有操作的消息将导致队列停止出队新的操作并向当前正在运行的任何操作发送取消消息。

在你的操作主方法中,应该检查isCancelled并在被取消时处理该状态。

有关更多信息,请参见线程编程指南中的创建和管理操作对象


但是请查看其他答案,听起来在使用NSInvocationOperation时,您不能以标准方式检查isCancelled - jrdioko

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接