方法1:在UI線程中同步加載網絡圖片
- UIImageView *headview = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
- NSURL *photourl = [NSURL URLWithString:@"http://www.exampleforphoto.com/pabb/test32.png"];
- //url請求實在UI主線程中進行的
- UIImage *images = [UIImage imageWithData:[NSData dataWithContentsOfURL:photourl]];//通過網絡url獲取uiimage
- headview.image = images;
這是最簡單的,但是由於在主線程中加載,會阻塞UI主線程。所以可以試試NSOperationQueue,一個NSOperationQueue 操作隊列,就相當於一個線程管理器,而非一個線程。因為你可以設置這個線程管理器內可以並行運行的的線程數量等等。
方法2:使用NSOperationQueue異步加載
- 下面就是使用NSOperationQueue實現子線程加載圖片:
- - (void)viewDidLoad
- {
- [super viewDidLoad];
- NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init];
- self.imageview = [[[UIImageView alloc] initWithFrame:CGRectMake(110, 50, 100, 100)] autorelease];
- [self.imageview setBackgroundColor:[UIColor grayColor]];
- [self.view addSubview:self.imageview];
- NSInvocationOperation *op = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(downloadImage) object:nil];
- [operationQueue addOperation:op];
- }
- - (void)downloadImage
- {
- NSURL *imageUrl = [NSURL URLWithString:HEADIMAGE_URL];
- UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:imageUrl]];
- self.imageview.image = image;
- }
不過這這樣的設計,雖然是異步加載,但是沒有緩存圖片。重新加載時又要重新從網絡讀取圖片,重復請求,實在不科學,所以可以考慮第一次請求時保存圖片。
