创建一个数组的图片,图片是在UITableViewController
的cellForRowInIndexPath
方法中异步检索到的。
但是数组要么不能完全充填,要么就顺序错误。
tableview:cellForRowAtIndexPath
中的代码:
// populate the cell's image
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
dispatch_async(queue, ^{
NSURL *url = [NSURL URLWithString:[newsModel url]];
NSData *data = [NSData dataWithContentsOfURL:url];
img = [[UIImage alloc] initWithData:data] ;
[imageArray insertObject:img atIndex:[indexPath row]];
dispatch_sync(dispatch_get_main_queue(), ^{
// make image standard size
CGSize imageSize = CGSizeMake(40, 40);
UIGraphicsBeginImageContext(imageSize);
CGRect imageRect = CGRectMake(0.0, 0.0, imageSize.width, imageSize.height);
[img drawInRect:imageRect];
cell.imageView.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[cell setNeedsLayout];
});
});
其中 imageArray (NSMutableArray)和img (UIImage)都是__bool类型的。
建议封装一个专门异步加载的UIImageView.这样使你的程序更易复用,更简洁.更关注于创建UITableViewcell的逻辑. 你也不用重复造轮子,有一些第三方库可以使用,如EGOImageview等