Objective-C-NSOperation自定义实现
2016-03-03 00:00
561 查看
摘要: NSOperation自定义子类
自定义 NSOperation要实现main方法,内部代码加上 autoRelease
DownloadImg.h
DownloadImg.m
ViewController
自定义 NSOperation要实现main方法,内部代码加上 autoRelease
DownloadImg.h
@class UIImage; @class DownLoadOperation; @protocol DownLoadOperationDelegate <NSObject> @required - (void) downloadOperation:(DownLoadOperation*) opertaion finishDownloadImg:(UIImage *)img; @end @interface DownLoadOperation : NSOperation /** 要传递到operation中的属性*/ @property (nonatomic, strong) NSString *urlStr; /** 用来通知下载图片生成KO*/ @property (nonatomic, weak) id<DownLoadOperationDelegate> delegate; @end
DownloadImg.m
#import <UIKit/UIKit.h> @implementation DownLoadOperation - (void) main { @autoreleasepool { if (self.isCancelled) { return; } NSURL *url = [NSURL URLWithString:self.urlStr]; NSData *data = [NSData dataWithContentsOfURL:url]; UIImage *img = [UIImage imageWithData:data]; if (self.isCancelled) { return; } //update UI [[NSOperationQueue mainQueue] addOperationWithBlock:^{ if ([self.delegate respondsToSelector:@selector(downloadOperation:finishDownloadImg:)]) { [_delegate downloadOperation:self finishDownloadImg:img]; } }]; } } @end
ViewController
#import "DownLoadOperation.h" @interface ViewController ()<DownLoadOperationDelegate> @property (weak, nonatomic) IBOutlet UIImageView *imgView; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; } - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { if (_imgView.image) { return; } DownLoadOperation *operation = [[DownLoadOperation alloc] init]; operation.urlStr = @"http://img4.duitang.com/uploads/item/201406/01/20140601231235_WRKGW.jpeg"; operation.delegate = self; NSOperationQueue *queue = [[NSOperationQueue alloc] init]; [queue addOperation:operation]; } - (void)downloadOperation:(DownLoadOperation *)opertaion finishDownloadImg:(UIImage *)img { _imgView.image = img; } @end
相关文章推荐
- Python3写爬虫(四)多线程实现数据爬取
- 峰回路转,Firefox 浏览器即将重返 iOS 平台
- 峰回路转,Firefox 浏览器即将重返 iOS 平台
- 不可修补的 iOS 漏洞可能导致 iPhone 4s 到 iPhone X 永久越狱
- iOS 12.4 系统遭黑客破解,漏洞危及数百万用户
- 每日安全资讯:NSO,一家专业入侵 iPhone 的神秘公司
- [转][源代码]Comex公布JailbreakMe 3.0源代码
- C#实现多线程的同步方法实例分析
- 浅谈chuck-lua中的多线程
- C#简单多线程同步和优先权用法实例
- C#多线程学习之(四)使用线程池进行多线程的自动管理
- C#多线程编程中的锁系统(三)
- C#多线程学习之(六)互斥对象用法实例
- 基于一个应用程序多线程误用的分析详解
- C#多线程学习之(三)生产者和消费者用法分析
- C#多线程学习之(一)多线程的相关概念分析
- C#多线程之Thread中Thread.IsAlive属性用法分析
- 分享我在工作中遇到的多线程下导致RCW无法释放的问题
- C#多线程编程之使用ReaderWriterLock类实现多用户读与单用户写同步的方法