多线程:NSOperation 的高级功能

本文介绍了一个iOS应用中处理大量触控事件的方法,使用NSOperationQueue管理多个异步任务,确保了良好的用户体验。文章详细展示了如何通过Objective-C实现触控事件的异步处理,并提供了暂停和取消所有操作的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#import "ViewController.h"

@interface ViewController ()
@property (nonatomic, strong) NSOperationQueue *queue;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self opDemo];
}

- (void)opDemo {

    for (int i = 0; i < 200; ++i) {

        [self.queue addOperationWithBlock:^{
            //设置休眠
            [NSThread sleepForTimeInterval:1.f];
            NSLog(@"%@ -- %d",[NSThread currentThread],i);
        }];
    }
}

// 暂停 or 继续
- (IBAction)pauseAndContinue:(id)sender {
    // 如果队列中没有操作,不让暂停
    if (self.queue.operationCount == 0) {
        NSLog(@"队列中没有操作,不需要暂停");
        return;
    }
    /*
     1. 暂停的是队列,如果操作已经在执行,不受影响,只会暂停还没有(准备)执行的操作
     */
    self.queue.suspended = !self.queue.isSuspended;
    if (self.queue.isSuspended)
    {
        NSLog(@"暂停");
    }else{
        NSLog(@"继续");
    }
}

- (IBAction)cancelAllOperation:(id)sender {
    NSLog(@"取消全部");
    // 取消所有的操作(准备执行,也就是还没执行的操作)

    // 想要取消正在执行:只能通过自定义操作来完成NSOperation
    [self.queue cancelAllOperations];
}

- (NSOperationQueue *)queue {
    if (_queue == nil) {
        _queue = [[NSOperationQueue alloc]init];
        // 设置最大并发
        /*
         1. 最大并发数不代表是线程数
         2. 最大并发数是同时开启多少条线程
         */
        _queue.maxConcurrentOperationCount = 2;
    }
    return _queue;
}

@end
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值