在iOS中加载网络图片有多种方式:
法1:在主线程中同步加载网络图片
在主线程中加载图片,先将图片的URL存放进NSURL,然后再用这个NSURL初始化NSData,再把UIImage用NSData初始化,就行了。代码如下:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
if ([tableView isEqual:self.tableView]) {
cell.textLabel.text = @"Synchronized Loading";
// synchronized image loading
NSURL *imageURL = [NSURL URLWithString:@"http://www.i-programmer.info/images/stories/News/2011/MARCH/CMULOGO.jpg"];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
cell.imageView.image = [UIImage imageWithData:imageData];
}
return cell;
}
但是这种方法会阻塞主线程,也就是只有