美文网首页
多线程-自定义Operation

多线程-自定义Operation

作者: ShenYj | 来源:发表于2016-08-22 16:17 被阅读308次

1.创建自定义Operation类,继承自NSOperation
2.重写自定义Operation的main方法
重写- (void)main方法,在里面实现想执行的任务
创建自动释放池(因为如果是异步操作,无法访问主线程的自动释放池),新版本已经不再需要手动创建自动释放池
3.通过 "- (BOOL)isCancelled" 方法检测操作是否被取消,对取消做出响应
之前提到过NSOperation只能对还未执行的任务做取消操作,是由于系统封装的方法内部我们无法访问,而自定义Operation中,我们需要重写main方法,在这里检测到isCancelled属性为YES时,直接返回,不执行后面的操作即可取消正在执行的操作,虽然能够实现取消正在执行的操作,但并不是立刻停止的,而是在调用了 operation 的 cancel 方法之后的下一个 isCancelled 的检查点取消的
4.在controller中调用start方法,或者添加到队列, main方法会被调用


  • 通过自定义Operation, 模拟异步下载图片

1.自定义DownloadOperation类,继承自NSOperation
2.声明属性

// url地址
@property (nonatomic,copy) NSString *urlString;
// 完成回调
@property (nonatomic,copy) void(^completeHandler)(UIImage *img);

3.在DownloadOperation类中重写main方法:

#import "DownloadOperation.h"

@implementation DownloadOperation

- (void)main{
    
    //@autoreleasepool {
    // 更新后不再需要手动创建,系统内部做过优化
    //}
    NSAssert(self.completeHandler != nil, @"completeHandler == nil");

    // 下载图片
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:self.urlString]];
    UIImage *image = [UIImage imageWithData:data];
    
    // 取消操作
    if (self.isCancelled) {
        NSLog(@"取消操作");
        return;
    }
    // 返回主线程刷新UI
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
       
        self.completeHandler(image);
    }];
}

@end

4.使用:

#import "ViewController.h"
#import "DownloadOperation.h"


@interface ViewController ()

@end

@implementation ViewController{
    
    NSOperationQueue *_queue;
    UIImageView *_imageView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
   
    _queue = [[NSOperationQueue alloc] init];
    _imageView = [[UIImageView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    _imageView.contentMode = UIViewContentModeCenter;
    [self.view addSubview:_imageView];
    
    // 1.创建自定义的Operation对象 (下载图片操作)
    DownloadOperation *operation = [[DownloadOperation alloc] init];
    
    operation.urlString = @"http://t1.mmonly.cc/mmonly/2014/201407/129/7.jpg";
    [operation setCompleteHandler:^(UIImage *img) {
        
        // 更新UI
        _imageView.image = img;
    }];
    
    // 2.把操作添加到队列中
    [_queue addOperation:operation];
    
}


@end

示例代码中先通过alloc]init实例化了操作对象,再通过属性完成参数传递和下载图片的回调
在使用系统为我们提供的NSOperation子类中,系统提供了类方法直接使用,所以为了方便使用,同样可以自定义一个类方法,完成参数传递和回调, 结合操作的取消一同进行演示


代码优化(自定义类方法):

.h

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

@interface DownloadOperation : NSOperation

// url地址
@property (nonatomic,copy) NSString *urlString;
// 完成回调
@property (nonatomic,copy) void(^completeHandler)(UIImage *img);

// 下载图片类方法
+(instancetype)downloadImageUrlString:(NSString *)urlString completeHandler:(void(^)(UIImage *img))completeHandler;

@end

.m

#import "DownloadOperation.h"


@implementation DownloadOperation

- (void)main{
    
    NSAssert(self.completeHandler != nil, @"completeHandler == nil");
    
    // 下载图片
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:self.urlString]];
    UIImage *image = [UIImage imageWithData:data];
    
    // 取消操作
    if (self.isCancelled) {
        NSLog(@"取消操作");
        return;
    }
    // 返回主线程刷新UI
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
        
        self.completeHandler(image);
    }];
}

// 自定义类方法下载图片

+ (instancetype)downloadImageUrlString:(NSString *)urlString completeHandler:(void (^)(UIImage *))completeHandler{
    
    DownloadOperation *operation = [[DownloadOperation alloc] init];
    operation.urlString = urlString;
    operation.completeHandler = completeHandler;
    return operation;
    
}

@end

外界调用:

#import "ViewController.h"
#import "DownloadOperation.h"

@interface ViewController ()

@end

@implementation ViewController{
    
    NSOperationQueue *_queue;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _queue = [[NSOperationQueue alloc] init];
    _queue.maxConcurrentOperationCount = 3;
    
    for (int i = 0; i < 20; i ++) {
        
        // 1.创建自定义的Operation对象
        DownloadOperation *operation = [DownloadOperation downloadImageUrlString:@"http://t1.mmonly.cc/uploads/tu/201607/tt/1alqhs1gwxo.jpg" completeHandler:^(UIImage *img) {
            NSLog(@"%d --> (%@)",i,[NSThread currentThread]);
        }];
        
        
        // 2.把操作添加到队列中
        [_queue addOperation:operation];
    }
    
}

// 触摸屏幕时取消所有操作(包括正在执行的操作)
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [_queue cancelAllOperations];
}

@end

相关文章

  • 多线程-Operation

    多线程之Operation 本文参考 reywenderlich 的一篇文章和demo介绍自定义operation...

  • Swift 5.x 多线程

    Swift多线程编程方案: Thread Cocoa Operation (Operation 和 Operati...

  • 多线程-自定义Operation

    1.创建自定义Operation类,继承自NSOperation2.重写自定义Operation的main方法重写...

  • iOS多线程操作:NSOperation

    Operation也是我们常见的多线程操作方式之一,在许多知名框架的多线程操作都是使用的Operation这种操作...

  • IOS多线程

    多线程技术 Thread 给线程加锁使线程同步 Operation

  • 多线程Operation

    NSOperation的作用配合使用NSOperation和NSOperationQueue也能实现多线程编程NS...

  • NSOperation的那些事

    自定义operation 根据文档,每一个operation都必须实现一下方法: 继承NSOperation类,重...

  • iOS-Swift相关

    swift程序. 1.Swift多线程之Operation:异步加载CollectionView图片2.Swift...

  • 多线程之operation

    1.NSOperation简介NSOperation是苹果公司对于GCD的封装,比GCD更简单易用、代码可读性也更...

  • 多线程 NSThread - Operation

    1.NSThread 每个NSThread对象对应一个线程,真正最原始的线程。 优点:NSThread轻量级最低,...

网友评论

      本文标题:多线程-自定义Operation

      本文链接:https://www.haomeiwen.com/subject/secgsttx.html