iOS 多线程技术2

发布时间:2017-09-11 13:03:56
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 = @; 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:]

这里写图片描述

企业建站2800元起,携手武汉肥猫科技,做一个有见地的颜值派!更多优惠请戳:武汉做网站多少钱 http://www.45qun.com