NSOperation
ViewController
(void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.//隊列 NSOperationQueue
//任務 NSOperation
// NSInvocationOperation
// NSBlockOperation
// 自定義任務 : NSOperation//A
NSInvocationOperation *invocationOper = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(invocationSel) object:nil];//把任務加入到隊列
NSOperationQueue *queue = [[NSOperationQueue alloc] init];//B
NSBlockOperation *blockOper = [NSBlockOperation blockOperationWithBlock:^{
NSInteger i = 0;
while (i < 100) {
NSLog(@”%ld”,i++);
}
NSLog(@”%@”,[NSThread currentThread]);
}];//依賴 必須在加入隊列之前
//blockOper 任務執行完成 在執行 invocationOper
[invocationOper addDependency:blockOper]; //後面先執行//最大任務數
//[queue setMaxConcurrentOperationCount:2];
// [queue addOperation:invocationOper];
// [queue addOperation:blockOper];
//image
self.imageView = [[UIImageView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:self.imageView];
TQCustomOperation *oper = [[TQCustomOperation alloc] initWithBlock:^(id obj) {
//刷新UI
NSLog(@"%@",[NSThread currentThread]);
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
NSLog(@"%@",[NSThread currentThread]);
self.imageView.image = [UIImage imageWithData:obj];
}];
}];
[queue addOperation:oper];
}
-(void)invocationSel
{
NSInteger i = 999;
while (i < 1100) {
NSLog(@”%ld”,i++);
}
NSLog(@”%@”,[NSThread currentThread]);
}
TQCustomOperation.m
@implementation TQCustomOperation
{
returnData _block;
}
-(id)initWithBlock:(returnData)block
{
self = [super init];
if (self) {
_block = block;
}
return self;
}
-(void)main
{
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@”http://d.hiphotos.baidu.com/news/q%3D100/sign=2866acb5560fd9f9a6175169152fd42b/203fb80e7bec54e7f54f99d7be389b504ec26a5c.jpg“]];
if(_block != nil)
{
_block(data);
}
}
@end