"vc控制器"
#import "ViewController.h"
#import "DownloaderOperation.h"
@interface ViewController ()
@property (nonatomic, strong) NSOperationQueue *queue;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.queue = [[NSOperationQueue alloc] init];
NSString *URLString = @"http://cdn.duitang.com/uploads/item/201601/09/20160109170639_wkEfa.jpeg";
void (^successBlock)() = ^(UIImage *image){
NSLog(@"%@ - %@",image,[NSThread currentThread]);
};
DownloaderOperation *op = [DownloaderOperation downloaderOperationWithURLString:URLString successBlock:successBlock];
[self.queue addOperation:op];
}
"DownloaderOperation.h"
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface DownloaderOperation : NSOperation
/**
实例化自定义操作对象的主方法
@param URLString 接收VC传入的图片地址
@param successBlock 接收VC传入的下载完成的代码块
@return 返回自定义的操作对象
*/
+ (instancetype)downloaderOperationWithURLString:(NSString *)URLString successBlock:(void(^)(UIImage *image))successBlock;
@end
DownloaderOperation.m
#import "DownloaderOperation.h"
@interface DownloaderOperation ()
@property (nonatomic, copy) NSString *URLString;
@property (nonatomic, copy) void(^successBlock)(UIImage *image);
@end
@implementation DownloaderOperation
+ (instancetype)downloaderOperationWithURLString:(NSString *)URLString successBlock:(void (^)(UIImage *))successBlock
{
DownloaderOperation *op = [[DownloaderOperation alloc] init];
op.URLString = URLString;
op.successBlock = successBlock;
return op;
}
- (void)main
{
NSLog(@"传入 %@",self.URLString);
NSURL *URL = [NSURL URLWithString:self.URLString];
NSData *data = [NSData dataWithContentsOfURL:URL];
UIImage *image = [UIImage imageWithData:data];
NSAssert(self.successBlock != nil, @"图片下载完成的回调不能为空!");
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
self.successBlock(image);
}];
}
@end