本篇将从四个方面对iOS开发中使用到的NSOperation技术进行讲解:一、什么是NSOperation二、我们为什么使用NSOperation三、在实际开发中如何使用NSOperation 1、自定义NSOperation 2、NSOperation的基本使用 3、NS ...
本篇将从四个方面对iOS开发中使用到的NSOperation技术进行讲解:
一、什么是NSOperation
二、我们为什么使用NSOperation
三、在实际开发中如何使用NSOperation
1、自定义NSOperation
2、NSOperation的基本使用
3、NSOperation实现线程间通信
1)利用代理进行消息传递
2)利用通知实现消息传递
3)利用block进行消息传递
四、与GCD比较
一、什么是NSOperation
NSOperation是一个抽象的基类,表示一个独立的计算单元,可以为子类提供有用且线程安全的建立状态,优先级,依赖和取消等操作。系统已经给我们封装了NSBlockOperation和NSInvocationOperation这两个实体类。使用起来也非常简单,不过我们更多的使用是自己继承并定制自己的操作。
二、我们为什么使用NSOperation
在iOS开发中,为了提升用户体验,我们通常会将操作耗时的操作放在主线程之外的线程进行处理。对于正常的简单操作,我们更多的是选择代码更少的GCD,让我们专注于自己的业务逻辑开发。NSOperation在ios4后也基于GCD实现,但是相对于GCD来说可控性更强,并且可以加入操作依赖。
三、在实际开发中如何使用NSOperation
1、自定义NSOperation
在实际开发中,系统提供的NSOperation可能无法满足我们的需求,这时,我们就需要自定义我们自己的NSOperation
@interface ViewController ()@property (nonatomic, weak) IBOutlet UIImageView *imageView;@end@implementation ViewController- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { NSLog(@"touchesBegan------%@", [NSThread currentThread]); if (!self.imageView.image) { // 避免重复下载,增强用户体验 NSOperationQueue *queue = [[NSOperationQueue alloc] init]; [queue setMaxConcurrentOperationCount:6]; MyOperation *myO = [[MyOperation alloc] init]; myO.imageView = self.imageView; [queue addOperation:myO]; } NSLog(@"end");}// 自定义NSOperation@interface MyOperation : NSOperation@property (nonatomic, strong) UIImageView *imageView;@end// 实现自定义NSOperation@implementation MyOperation- (void)main { NSLog(@"%s----%@", __func__, [NSThread currentThread]); UIImage *image = [self downLoadImage:@"http://g.hiphotos.baidu.com/image/pic/item/f31fbe096b63f624cd2991e98344ebf81b4ca3e0.jpg"]; dispatch_async(dispatch_get_main_queue(), ^{ NSLog(@"%@======%@", image, [NSThread currentThread]); self.imageView.image = image; });}- (UIImage *)downLoadImage:(NSString *)urlString { NSLog(@"%s----%@",__func__, [NSThread currentThread]); NSURL *url = [NSURL URLWithString:urlString]; NSData *data = [NSData dataWithContentsOfURL:url]; UIImage *image = [UIImage imageWithData:data]; NSLog(@"图片下载完成"); return image;}@end
海外公司注册、海外银行开户、跨境平台代入驻、VAT、EPR等知识和在线办理:https://www.xlkjsw.com
原标题:iOS开发之多线程技术——NSOperation篇
关键词:IOS
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们:
admin#shaoqun.com
(#换成@)。