线程间通讯

 

 

#import "ViewController.h"网络

 

@interface ViewController ()并发

 

@property (weak, nonatomic) IBOutlet UIImageView *imageView;atom

@property (nonatomic,strong) NSOperationQueue *queue;url

 

@endspa

 

@implementation ViewController线程

 

// 懒加载一个非主队列继承

-(NSOperationQueue *)queue队列

{图片

    if (!_queue) {ip

        _queue = [[NSOperationQueue alloc] init];

        

        // 设置队列的最大并发数

        [_queue setMaxConcurrentOperationCount:6];

        

    }

    return _queue;

}

 

 

- (void)viewDidLoad {

    [super viewDidLoad];

    

    // 自定义 NSOperation

    // 自定义步骤: 继承自 NSOperation. 重写 main 方法.

}

 

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

{

    // 在子线程下载图片

    

    // 建立操做

    

    __weak typeof(self) wself = self;

    NSBlockOperation *op = [NSBlockOperation blockOperationWithBlock:^{

        

        // 下载.

        UIImage *image = [self downloadWebImageWithUrlString:@"http://pic1.nipic.com/2008-09-08/200898163242920_2.jpg"];

        

        // 回到主线程显示图片

        [[NSOperationQueue mainQueue] addOperationWithBlock:^{

            

            NSLog(@"显示图片%@",[NSThread currentThread]);

            // 显示图片

            wself.imageView.image = image;

            

        }];

        

    }];

    

    // 将操做添加到非主队列中

    [self.queue addOperation:op];

    

    // 在主线程显示图片

}

 

 

 

// 下载网络图片的方法

- (UIImage *)downloadWebImageWithUrlString:(NSString *)urlString

{

    NSLog(@"downloadWebImageWithUrlString:%@",[NSThread currentThread]);

    

    NSURL *url = [NSURL URLWithString:urlString];

    

    NSData *data = [NSData dataWithContentsOfURL:url];

    

    UIImage *image = [UIImage imageWithData:data];

    

    return image;

}

 

@end

相关文章
相关标签/搜索