框架名為:UIImage+WebCache.h 繼承於UIimageView
框架裡面加載網絡圖片的方法共4中:分別為1.普通加載 2.線程NSThread 3.
#import "ViewController.h"
#import "UIImage+WebCache.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
imageArray = [NSMutableArray array];
for(int i = 0;i < 5;i++){
for(int j = 0;j < 6;j++){
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(j*65 +5, i*64 +10, 60, 60)];
imageView.backgroundColor = [UIColor cyanColor];
[self.view addSubview:imageView];
[imageArray addObject:imageView];
}
}
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(160, 400, 80, 30);
[button setTitle:@"載入" forState:UIControlStateNormal];
[button addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
}
- (void)buttonAction{
for(UIImageView *imageView in imageArray){
NSString *string = @"http://img3.douban.com/view/photo/photo/public/p2221339563.jpg";
NSURL *url = [NSURL URLWithString:string];
[imageView setImageWithURL:url];
}
}
#import
@interface UIImageView (WebCache)
- (void)setImageWithURL:(NSURL *)url;
@end
#import "UIImage+WebCache.h"
@implementation UIImageView (WebCache)
- (void)setImageWithURL:(NSURL *)url{
//第一種方法:普通的加載
/*
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
[self setImage:image];
*/
//第二種方法:線程
//NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(loadImage:) object:url];
//[thread start];
//第三種方法:隊列
/* NSOperationQueue *queue = [[NSOperationQueue alloc] init];
//操作數
NSBlockOperation *op = [NSBlockOperation blockOperationWithBlock:^{
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
//使用主隊列來回到主線程
//在主線程上修改UI
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
//修改UI界面
[self setImage:image];
}];
}];
[queue addOperation:op];
*/
//----------------GCD---------------
// //1.創建Queue
// dispatch_queue_t queue = dispatch_queue_create("com.xw.gcd.queue", DISPATCH_QUEUE_CONCURRENT);//並行隊列
//
// //2.創建要執行的任務,加到隊列中
// dispatch_async(queue, ^{
//
// NSData *data = [NSData dataWithContentsOfURL:url];
// UIImage *image = [UIImage imageWithData:data];
// [self setImage:image];
// });
//用系統給的queue---
// (兩個參數)
//參數1:優先級
//參數2:標識符
dispatch_queue_t globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(globalQueue, ^{
//請求數據
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
//顯示在UI界面上
dispatch_async(dispatch_get_main_queue(), ^{
//UI相關的代碼
//UI界面的刷新最好回到主線程中
[self setImage:image];
});
});
}
- (void)loadImage:(NSURL *)url{
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
[self setImage:image];
}
@end