自定义NSOperation 操作
2015-12-03 00:00
204 查看
摘要: operation 都会在main 这个方法中执行
#import <Foundation/Foundation.h>
@class HMDownloadOperation;
@protocol HMDownloadOperationDelegate <NSObject>
@optional
- (void)downloadOperation:(HMDownloadOperation *)operation didFinishDownload:(UIImage *)image;
@end
@interface HMDownloadOperation : NSOperation
@property (nonatomic, copy) NSString *imageUrl;
@property (nonatomic, strong) NSIndexPath *indexPath;
@property (nonatomic, weak) id<HMDownloadOperationDelegate> delegate;
@end
#import "HMDownloadOperation.h"
@implementation HMDownloadOperation
- (void)main
{
@autoreleasepool {
if (self.isCancelled) return;
NSURL *url = [NSURL URLWithString:self.imageUrl];
NSData *data = [NSData dataWithContentsOfURL:url]; // 下载
UIImage *image = [UIImage imageWithData:data]; // NSData -> UIImage
if (self.isCancelled) return;
// 回到主线程
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
if ([self.delegate respondsToSelector:@selector(downloadOperation:didFinishDownload:)]) {
[self.delegate downloadOperation:self didFinishDownload:image];
}
}];
}
}
@end
#import <Foundation/Foundation.h>
@class HMDownloadOperation;
@protocol HMDownloadOperationDelegate <NSObject>
@optional
- (void)downloadOperation:(HMDownloadOperation *)operation didFinishDownload:(UIImage *)image;
@end
@interface HMDownloadOperation : NSOperation
@property (nonatomic, copy) NSString *imageUrl;
@property (nonatomic, strong) NSIndexPath *indexPath;
@property (nonatomic, weak) id<HMDownloadOperationDelegate> delegate;
@end
#import "HMDownloadOperation.h"
@implementation HMDownloadOperation
- (void)main
{
@autoreleasepool {
if (self.isCancelled) return;
NSURL *url = [NSURL URLWithString:self.imageUrl];
NSData *data = [NSData dataWithContentsOfURL:url]; // 下载
UIImage *image = [UIImage imageWithData:data]; // NSData -> UIImage
if (self.isCancelled) return;
// 回到主线程
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
if ([self.delegate respondsToSelector:@selector(downloadOperation:didFinishDownload:)]) {
[self.delegate downloadOperation:self didFinishDownload:image];
}
}];
}
}
@end
相关文章推荐
- OpenCV安装
- OpenCV - "dyld: Library not loaded: cv2.so"
- hadoop的体系结构 hadoop hdfs 命令
- Linux编程常见错误及解决方案
- Linux中断研究
- MAC OS上使用OpenGL遇到的大坑
- 领域驱动设计实战—基于DDDLite的权限管理OpenAuth.net
- 用 tornado 做网站 (7)
- Force StyleCop to Ignore a File
- mvc项目架构分享系列之架构搭建初步
- centos7使用无线wifi连接
- exceptions and solutions when installing local hadoop
- squid.conf 的cache_peer 详解
- 第二十天-linux系统用户权限集中管理方案
- gcc解析
- squid 访问日志记录
- linux ubuntu 下c++ 开发环境
- Linux磁盘管理之创建磁盘分区05
- Linux内存调试工具初探-MEMWATCH
- Deep Learning + Opencv + 机器视觉