OGeek|极客世界-中国程序员成长平台

标题: ios - 取消的操作仍在运行 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 23:58
标题: ios - 取消的操作仍在运行

我需要取消操作队列中的所有操作。但在调用 cancelAllOperation 方法后,操作仍在运行。 简单的例子:

@interface MyOperation : NSOperation
@end
@implementation MyOperation
-(void)main {
  NSLog(@"starting 1");
  sleep(4);
  NSLog(@"finished 1");
}
@end
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
   [super viewDidLoad];
   NSOperationQueue *queue = [[NSOperationQueue alloc] init];
   MyOperation *op = [MyOperation new];
   [queue addOperationp];
   sleep(2);
   [queue cancelAllOperations];
   NSLog(@"canceled");
}
log:
2014-07-23 09:55:48.839 MDict1[837:1303] starting 1
2014-07-23 09:55:50.842 MDict1[837:70b] canceled
2014-07-23 09:55:52.842 MDict1[837:1303] finished 1



Best Answer-推荐答案


取消操作不会唤醒 sleep 调用。在 viewDidLoad 中调用 sleep 是不好的。永远不要在主线程上休眠。

正确的解决方案是你的操作的main方法的实现需要检查self是否已经被取消。如果是,则需要返回。

一个粗略的例子可能是:

- (void)main {
    while (!self.isCancelled) {
        // do some repeated operation
    }
}

同样,当它看到它已被取消时,它有责任停止自己的操作。队列实际上并没有杀死任何操作。

来自 NSOperationQueue cancelAllOperations 的文档(强调我的):

This method sends a cancel message to all operations currently in the queue. Queued operations are cancelled before they begin executing. If an operation is already executing, it is up to that operation to recognize the cancellation and stop what it is doing.

关于ios - 取消的操作仍在运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24901402/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4