lazy懶加載(延遲加載)UITableView
打個比方,當我們刷網易新聞App時,滿屏的新聞並非每條都對胃口,很多時候我們只是快速滑過。如果一滑過就急著加載圖片,既浪費內存又拖累流暢度,用戶體驗自然打折。這時候就可以引入lazy加載:滑動過程或減速途中都不加載圖片,只有當用戶停下手指、減速也結束時,才真正發起加載。
我曾用SDWebImage來做異步加載,測試時卻踩到了重用的坑。SDWebImage雖然實現了異步加載與緩存,但在懶加載場景下,滑動過程完全沒有網絡請求,cell上的圖片便會發生重用;等停下來能發請求時,圖片才會變回當前cell應有的樣子,中間有大概1到2秒的「空窗期」(本質上是還沒發請求,並非緩存問題)。
解決辦法是在Model對象中定義一個UIImage屬性,異步下載完成後,用已緩存在沙盒中的圖片路徑為它賦值。這樣在cellForRowAtIndexPath中判斷這個UIImage是否為空:為空就發網絡請求,不為空就直接賦給cell的imageView,短暫重用的問題便迎刃而解。
下面用自寫的異步加載緩存類來演示(相對於SDWebImage,這裡需要拿到圖片在沙盒中的存儲路徑,以便實現懶加載)。
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 * item = [[NewsItem alloc] initWithDictionary:newsDic];
[resultArray addObject:item];
[item release];
}
return resultArray;
}
@end
圖片下載類:
#import <Foundation/Foundation.h>
@class NewsItem;
@interface ImageDownloader : NSObject
@property (nonatomic,copy) NSString * imageUrl;
@property (nonatomic,retain) NewsItem * newsItem; //下載圖像所屬的新聞
@property (nonatomic,copy) void (^completionHandler)(void); //block回調
- (void)startDownloadImage:(NSString *)imageUrl;
- (UIImage *)loadLocalImage:(NSString *)imageUrl;
@end
#import "ImageDownloader.h"
#import "NewsItem.h"
@implementation ImageDownloader
- (void)dealloc
{
self.imageUrl = nil;
Block_release(_completionHandler);
[super dealloc];
}
- (void)startDownloadImage:(NSString *)imageUrl
{
self.imageUrl = imageUrl;
//先查本地沙盒,存在直接取,不存在再下載並保存
UIImage * image = [self loadLocalImage:imageUrl];
if (image == nil) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData * imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageUrl]];
[imageData writeToFile:[self imageFilePath:imageUrl] atomically:YES]; //緩存
dispatch_async(dispatch_get_main_queue(), ^{
UIImage * image = [UIImage imageWithData:imageData];
self.newsItem.newsPic = image;
if (_completionHandler) { _completionHandler(); }
});
});
}
}
- (UIImage *)loadLocalImage:(NSString *)imageUrl
{
self.imageUrl = imageUrl;
NSString * filePath = [self imageFilePath:self.imageUrl];
UIImage * image = [UIImage imageWithContentsOfFile:filePath];
if (image != nil) { return image; }
return nil;
}
- (NSString *)imageFilePath:(NSString *)imageUrl
{
NSString * cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSString * downloadImagesPath = [cachesPath stringByAppendingPathComponent:@"DownloadImages"];
NSFileManager * fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:downloadImagesPath]) {
[fileManager createDirectoryAtPath:downloadImagesPath withIntermediateDirectories:YES attributes:nil error:nil];
}
//URL含"/",需替換為"_"作為文件名
NSString * imageName = [imageUrl stringByReplacingOccurrencesOfString:@"/" withString:@"_"];
return [downloadImagesPath stringByAppendingPathComponent:imageName];
}
@end
控制器關鍵代碼(網絡請求、數據處理、自定義cell自行實現):
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = @"Cell";
NewsListCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier ];
if (!cell) {
cell = [[[NewsListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier] autorelease];
}
NewsItem * item = [_dataArray objectAtIndex:indexPath.row];
cell.titleLabel.text = item.newsTitle;
if (item.newsPic == nil) {
cell.picImageView.image = nil;
//懶加載關鍵:只有既不拖拽也不減速時才下載
if (self.tableView.dragging == NO && self.tableView.decelerating == NO) {
[self startPicDownload:item forIndexPath:indexPath];
}
}else{
cell.picImageView.image = item.newsPic; //有圖像直接展示
}
return cell;
}
//開始下載圖像
- (void)startPicDownload:(NewsItem *)item forIndexPath:(NSIndexPath *)indexPath
{
ImageDownloader * downloader = [[ImageDownloader alloc] init];
downloader.newsItem = item;
[downloader setCompletionHandler:^{
NewsListCell * cell = (NewsListCell *)[self.tableView cellForRowAtIndexPath:indexPath];
cell.picImageView.image = downloader.newsItem.newsPic;
}];
[downloader startDownloadImage:item.newsPicUrl];
[downloader release];
}
//加載當前可見cell的圖像
- (void)loadImagesForOnscreenRows
{
NSArray * visibleCells = [self.tableView indexPathsForVisibleRows];
for (NSIndexPath * indexPath in visibleCells) {
NewsItem * item = [_dataArray objectAtIndex:indexPath.row];
if (item.newsPic == nil) {
[self startPicDownload:item forIndexPath:indexPath];
}
}
}
//延遲加載關鍵:停止拖拽且不再減速時加載
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
if (!decelerate) {
[self loadImagesForOnscreenRows];
}
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
[self loadImagesForOnscreenRows];
}
下拉刷新與上拉加載的原理
很多App的新聞或列表都有下拉刷新、上拉加載的效果。網上有MJRefresh、EGOTableViewPullRefresh等成熟的第三方庫,用起来很方便。但閒暇之餘不妨想想:這種效果的原理到底是什麼?其實只要不是硬件問題,大部分效果都能在系統UI的基礎上做出來。
關鍵代碼分析如下:
// 下拉刷新原理
- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView
{
if (scrollView.contentOffset.y < - 100) {
[UIView animateWithDuration:1.0 animations:^{
//frame偏移,距離頂部150(可自行設定)
self.tableView.contentInset = UIEdgeInsetsMake(150.0f, 0.0f, 0.0f, 0.0f);
} completion:^(BOOL finished) {
//在此發起網絡請求,刷新數據
}];
}
}
// 上拉加載原理
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
//關鍵:contentSize.height永遠比contentOffset.y高一個屏幕;上拉到底再往上時產生的偏移量,
//能讓 contentOffset.y + 屏幕高度 大於 contentSize.height
if (scrollView.contentOffset.y + scrollView.frame.size.height >= scrollView.contentSize.height) {
[UIView animateWithDuration:1.0 animations:^{
//frame偏移,距離底部往上60(可自行設定)
self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 60, 0);
} completion:^(BOOL finished) {
//發起網絡請求加載更多;數據回來後把contentInset改回(0,0,0,0)
}];
}
}
由此可見,下拉刷新與上拉加載本質上就是借助contentOffset與contentInset的變化,配合動畫「騙」出直觀的交互效果。