iOS 多线程技术2

iOS 多线程技术2

NSOperation


  • NSInvocationOperation
        //创建一个队列
        NSOperationQueue *queue = [[NSOperationQueue alloc] init];

        //创建子任务,定义子任务必须是 NSOperation 的子类
        NSInvocationOperation *op = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(dosomething:) object:@"NSInvocationOperation"];

        //当把任务加入到队列后,自己主动开启线程
        [queue addOperation:op];
  • NSBlockOperation
            //创建一个队列
        NSOperationQueue *queue = [[NSOperationQueue alloc] init];

        //创建 NSBlockOperation 对象
        NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
        [self doSomething];
        }];

        //加入队列
        [queue addOperat:operation];

Demo:
以下我用NSOperation 的两种方法来创建一个样例,实现与上篇一样的功能,

#import "ViewController.h"

---

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *iamgeView;
@property (weak, nonatomic) IBOutlet UILabel *lable;


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

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    // 1.NSInvocationOperation
    NSInvocationOperation *op = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(dosomething:) object:@"NSInvocationOperation"];
    op.name = @"xiaoming";

    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    [queue addOperation:op];

    NSLog(@"%@",queue.operations);
    _queue = queue;
}

- (void)dosomething:(NSString*)str
{
  //耗时操作
    [NSThread sleepForTimeInterval:3];

    //须要在主线程中更新 UI
    [self performSelectorOnMainThread:@selector(updateLable:) withObject:str waitUntilDone:YES];
}
- (void)updateLable:(NSString*)str
{
    if ([[NSThread currentThread] isMainThread]) {
        NSLog(@"主线程>>>%s",__func__);
    }
    _lable.text = str;
}
- (IBAction)btnAction:(UIButton *)sender {

    NSBlockOperation *blockOp = [NSBlockOperation blockOperationWithBlock:^{
        //耗时操作
        [NSThread sleepForTimeInterval:3];

        //创建 url
        NSString *urlStr = @"http://img.hb.aicdn.com/5a8f57157b47284724d09ffd2da28369731f8144ac9c-1XdZKJ_fw658";
        NSURL *url = [NSURL URLWithString:urlStr];
        NSData *data = [NSData dataWithContentsOfURL:url];

        UIImage *image = [UIImage imageWithData:data];

        //更新 UI
        [self performSelectorOnMainThread:@selector(updateImageView:) withObject:image waitUntilDone:YES];
    }];
    [_queue addOperation:blockOp];
}
- (void)updateImageView:(UIImage*)img
{
    if ([[NSThread currentThread] isMainThread]) {
        NSLog(@"主线程>>>>>>%s",__FUNCTION__);
    }

    _iamgeView.image = img;
}

@end

执行结果:
2015-08-02 15:03:33.909 05-NSOperationDemo[3284:874300] (
“{name = ‘xiaoming’}”
)
2015-08-02 15:03:36.911 05-NSOperationDemo[3284:874300] 主线程>>>-[ViewController updateLable:]
2015-08-02 15:03:47.730 05-NSOperationDemo[3284:874300] 主线程>>>>>>-[ViewController updateImageView:]

这里写图片描写叙述


原文地址:https://www.cnblogs.com/cxchanpin/p/7228874.html