(1)最简单的下载,显示图片的方法:
[plain] view plaincopy
- UIImageView *imageView = [[UIImageView alloc] initWithFrame:[self.view bounds]];
- imageView.image = [self loadImageFromUrl:@"http://storage.live.com/items/72A00BF5A838647C!1616?filename=meinv004.jpg"];
- [self.view addSubview:imageView];
-
- -(UIImage*)loadImageFromUrl: (NSString*)url
- {
- NSURL *imageUrl = [NSURL URLWithString:url];
- NSData *imageData = [NSData dataWithContentsOfURL:imageUrl];
- UIImage *image = [UIImage imageWithData:imageData];
- return image;
- }
这种最简单的图片加载方式阻塞了main线程. 使得流程不能流畅进行.
(2)开辟线程来解决这个问题.
[plain] view plaincopy
- // set imageview
- UIImageView *imageView = [[UIImageView alloc] initWithFrame:[self.view bounds]];
- imageView.backgroundColor = [UIColor yellowColor];
- imageView.tag = imageView_tag;
- [self.view addSubview:imageView];
-
- // load image in background
- NSString *url = IMAGE_URL;
- [self performSelectorInBackground:@selector(loadImageFromUrl:) withObject:url];
-
-
-
- -(void)loadImageFromUrl: (NSString*)url {
- NSURL *imageUrl = [NSURL URLWithString:url];
- NSData *imageData = [NSData dataWithContentsOfURL:imageUrl];
- [self performSelectorOnMainThread:@selector(updateImageView:) withObject:imageData waitUntilDone:NO];
- }
- -(void) updateImageView:(NSData*) data {
- UIImageView *imageView = (UIImageView *)[self.view viewWithTag:imageView_tag];
- imageView.image = [UIImage imageWithData:data];
- }
并且只能在main线程中设置UI的内容, 所以代码量增加了较多. 代码量暂且不管, 这里还有一个比较严重的问题就是每次都要加载图片,
使用SDWebImage:
[plain] view plaincopy
- #import <SDWebImage/UIImageView+WebCache.h>
- [imageView setImageWithURL:[NSURL URLWithString:[_objects objectAtIndex:indexPath.row]]
- placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
SDWebImage可以实现: *下载和缓存图片. *相同的url不会被重复下载.
*坏的url不会一直请求.
|