自定义Operation子类

继承自 NSOperation:

//.h
@interface ImageOperation : NSOperation

//图片的url
@property (nonatomic,strong)NSString *urlString;
//图片视图对象
@property (nonatomic,strong)UIImageView *imageView;

@end

//.m

@implementation ImageOperation

//自定义NSOperation类型,需要实现main方法
//当队列调度操作执行时,会自动运行 main 方法
//注意:main 方法中需要使用自动释放池!
-(void)main
{
   @autoreleasepool {
        NSURL *url = [NSURL URLWithString:self.urlString];
        NSData *data = [NSData dataWithContentsOfURL:url];

        //在主线程刷新UI
        [self performSelectorOnMainThread:@selector(refreshUI:) withObject:data waitUntilDone:YES];
    }
}

- (void)refreshUI:(NSData *)data
{
    self.imageView.image = [UIImage imageWithData:data];
}

@end

//Practice
//创建线程下载图片
ImageOperation *op = [[ImageOperation alloc] init];
//图片的url
op.urlString = @"http://g.hiphotos.baidu.com/image/pic/item/4034970a304e251fb3145e6ca586c9177e3e5346.jpg";
//图片视图
op.imageView = _myImageView;

//添加到队列里面
[_queue addOperation:op];

results matching ""

    No results matching ""