線程間通訊

 

 

#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

相關文章
相關標籤/搜索