TableView 的优化
1 TableView 优化的原理:
当我们用APP 访问新闻的时候,新闻中的内容并不是我们都喜欢的内容,因此我们会快速的滑过,但是TableView的加载机制是只要用户滑过该条新闻,就会加载新闻.因此会让用户体验很差. TableView的优化目的就是当用户快速滑过自己不喜欢的内容的时候不加载该部分内容的图片,待滑动停止或者减速的时候才加载当前页面的图片.
2 实现过程:
当我们用 SDWebImage异步加载图片时,会出现重用的 BUG.这是因为虽然 SDWebImage 实现了异步加载缓存,但是当加载完图片后再次发送网络请求时会直接加载缓存中的图片.注意,如果是 lazy 加载的时候,滑动过程中是不进行网络请求的,cell 上的图片就会发生重用.当滑动停止的时候才会加载当前 cell 上的图片,但是会有1~2秒的延迟.解决办法就是在模型对象中定义一个 UIImage 属性,异步下载图片后,用已经缓存到沙盒的图片给他进行赋值,这样才能在cellForRowAtIndexPath方法中判断这个 UIImage 对象时候为空.若为空,则进行网络请求,不为空,则将它赋值给 cell 的imageView对象.这样就能解决图片短暂重用的问题.
3 代码实现过程
@model类 |
#import <foundation /foundation.h> |
@interface NewsItem : NSObject |
@property (nonatomic,copy) NSString * newsTitle; |
@property (nonatomic,copy) NSString * newsPicUrl; |
@property (nonatomic,retain) UIImage * newsPic; // 存储每个新闻自己的image对象 |
- (id)initWithDictionary:(NSDictionary *)dic; |
// 处理解析 |
+ (NSMutableArray *)handleData:(NSData *)data; |
@end |
#import "NewsItem.h" |
#import "ImageDownloader.h" |
@implementation NewsItem |
- (void)dealloc |
{ |
self.newsTitle = nil; |
self.newsPicUrl = nil; |
self.newsPic = nil; |
[super dealloc]; |
} |
- (id)initWithDictionary:(NSDictionary *)dic |
{ |
self = [super init]; |
if (self) { |
self.newsTitle = [dic objectForKey:@"title"]; |
self.newsPicUrl = [dic objectForKey:@"picUrl"]; |
|
//从本地沙盒加载图像 |
ImageDownloader * downloader = [[[ImageDownloader alloc] init] autorelease]; |
self.newsPic = [downloader loadLocalImage:_newsPicUrl]; |
} |
return self; |
} |
+ (NSMutableArray *)handleData:(NSData *)data; |
{ |
//解析数据 |
NSError * error = nil; |
NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error]; |
NSMutableArray * originalArray = [dic objectForKey:@"news"]; |
//封装数据对象 |
NSMutableArray * resultArray = [NSMutableArray array]; |
|
for (int i=0 ;i<[originalArray count]; i++) { |
NSDictionary * newsDic = [originalArray objectAtIndex:i]; |
NewsItem * ite |