我为我的项目创建的内容如下;
通过“UITableViewCell+Async.h”中的类别扩展 UITableViewCell 类
(如果你不确定 Obj C 中的类别是什么,请参阅一些示例)
@interface UITableViewCell (Async)
-(void)loadAsyncImage:(NSString*)url withIndex:(NSInteger)index inWidth:(NSInteger)width inHeight:(NSInteger)height;
-(void)loadAsyncBackground:(NSMutableArray*)parameters;
@end
然后在实现文件“UITableViewCell+Async.m”中
#import "UITableViewCell+Async.h"
@implementation UITableViewCell (Async)
-(void)loadAsyncImage:(NSString*)url
withIndex:(NSInteger)index
inWidth:(NSInteger)width
inHeight:(NSInteger)height {
NSMutableArray* parameters = [NSMutableArray arrayWithCapacity:2];
[parameters addObject:url];
[parameters addObject:[NSNumber numberWithInteger:index]];
[parameters addObject:[NSNumber numberWithInteger:width]];
[parameters addObject:[NSNumber numberWithInteger:height]];
self.imageView.tag = index;
[self performSelectorInBackground:@selector(loadAsyncBackground:) withObject:parameters];
}
-(void)loadAsyncBackground:(NSMutableArray*)parameters {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSString* url = [parameters objectAtIndex:0];
NSInteger index = [[parameters objectAtIndex:1] integerValue];
NSInteger width = [[parameters objectAtIndex:2] integerValue];
NSInteger height = [[parameters objectAtIndex:3] integerValue];
UIImage* image = [Utils getImageResized:url inSize:CGSizeMake(width, height)];
if (self.tag==index) {
self.imageView.image = image;
[self setNeedsLayout];
}
[pool release];
}
@end
这基本上向 UITableViewCell 添加了一项功能,以在新的后台线程中加载图像、调整图像大小并将其设置为 imageview。检查添加的标签以查看单元是否仍在等待图像,因为它可以重复使用,并且图像的另一个线程可能正在为该重复使用的单元下载另一个图像...
上述代码中的函数的签名为;
+(UIImage*)getImageResized:(NSString*)url inSize:(CGSize)size;
检查图像的本地缓存,如果缓存中没有图像,则从网络下载图像,将其保存到本地缓存,将图像调整为给定大小并返回图像,所有这些都在同步(阻塞)方法调用中完成。由于这已经是后台线程,因此阻止它执行此操作没有什么坏处。当该方法返回图像时,如果它仍然具有相同的标记,则将其设置为单元格的图像视图(不会重新用于其他行)
在 cellForRowAtIndexPath 方法中,您可以添加新类别,您应该完成;
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"......."];
if (cell == nil) {
................
}
................
[cell loadAsyncImage:deal.logo withIndex:indexPath.row inWidth:40 inHeight:40];
................
return cell;
}