继承NSOperation类完成能被cancel的耗时操作

本文介绍了如何使用NSOperation在iOS开发中实现并发任务,并通过设置操作完成块来控制任务流程。

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

//

//  MyOperation.h

//  NSOperation

//

//  Created by zmx on 16/1/8.

//  Copyright © 2016 zmx. All rights reserved.

//


#import <Foundation/Foundation.h>


@interface MyOperation : NSOperation


+ (instancetype)operationWithOpname:(NSString *)opname;


@end



//

//  MyOperation.m

//  NSOperation

//

//  Created by zmx on 16/1/8.

//  Copyright © 2016 zmx. All rights reserved.

//


#import "MyOperation.h"


@interface MyOperation ()


@property (nonatomic, copy) NSString *opname;


@end


@implementation MyOperation


+ (instancetype)operationWithOpname:(NSString *)opname {

    MyOperation *operation = [[super alloc] init];

    operation.opname = opname;

    return operation;

}


- (void)main {

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

        if (self.isCancelled) {

            return;

        }

        NSLog(@"%@--%d", self.opname, i);

    }

}


@end



//

//  ViewController.m

//  NSOperation

//

//  Created by zmx on 16/1/8.

//  Copyright © 2016 zmx. All rights reserved.

//


#import "ViewController.h"

#import "MyOperation.h"


@interface ViewController ()


@property (nonatomic, strong) NSOperationQueue *queue;


@end


@implementation ViewController


- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

    MyOperation *op1 = [MyOperation operationWithOpname:@"op1"];

    MyOperation *op2 = [MyOperation operationWithOpname:@"op2"];

    [op1 setCompletionBlock:^{

        NSLog(@"op1 finish");

    }];

    [op2 setCompletionBlock:^{

        NSLog(@"op2 finish");

    }];

    self.queue = [[NSOperationQueue alloc] init];

    [self.queue addOperation:op1];

    [self.queue addOperation:op2];

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

        [op2 cancel];

    });

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

        [op1 cancel];

    });

}


@end

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值