NSOperation

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

发布了83 篇原创文章 · 获赞 0 · 访问量 1万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章