• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

ios - 取消的操作仍在运行

[复制链接]
菜鸟教程小白 发表于 2022-12-12 23:58:22 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

我需要取消操作队列中的所有操作。但在调用 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/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap