一、什麼是延遲加載(Lazy Loading)
我們滑動新聞類 App 時常有這樣的困擾:手指飛快劃過,只想略過不感興趣的內容,可螢幕上每經過一則新聞,對應的配圖就急著開始下載。這樣的體驗既拖沓又白白消耗記憶體與流量。延遲加載的思路正是為了解決這個問題——在使用者拖曳或列表正在減速滑動時,一律不觸發圖片下載;只有在滑動完全停止、減速效果結束之後,才真正去載入當前螢幕可見的圖片。
最初我使用 SDWebImage 來做異步加載,測試時卻發現了「圖片重用」的 bug。SDWebImage 雖然具備異步下載與快取能力,載入過的圖片再次請求會直接命中快取;但延遲加載的關鍵在於滑動過程中完全不發起網路請求,於是 Cell 在重複使用時就會短暫顯示錯誤的圖片,直到你停下手指、真正觸發請求後才還原成該 Cell 應有的圖片,中間大約有一到兩秒的落差(嚴格說並非「延遲」,而是這段期間根本沒有發請求,也不是快取的問題)。
解決方式其實很直觀:在 Model 物件裡定義一個 UIImage 屬性,圖片異步下載完成後,把已快取到沙盒中的圖片賦值給它。如此一來,在 cellForRowAtIndexPath 中只需判斷這個 UIImage 是否為空——為空才發起網路請求,不為空則直接把圖片指定給 Cell 的 imageView,圖片短暫重用的問題便迎刃而解。
下面範例採用的是自寫的異步下載與快取類;至於 SDWebImage 的延遲加載寫法會在後續章節補充。之所以不用 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];
}
#pragma mark - 異步加載
- (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();
}
});
});
}
}
#pragma mark - 載入本地圖像
- (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;
}
#pragma mark - 取得圖片路徑
- (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:@"_"];
NSString *imageFilePath = [downloadImagesPath stringByAppendingPathComponent:imageName];
return imageFilePath;
}
@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];
}
- (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];
}
}
}
#pragma mark - 延遲加載關鍵
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
if (!decelerate) {
[self loadImagesForOnscreenRows];
}
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
[self loadImagesForOnscreenRows];
}
二、下拉刷新與上拉載入的原理
幾乎每個新聞或展示類 App 都具備下拉刷新、上拉載入的效果。網上有 MJRefresh、EGOTableViewPullRefresh 等成熟的第三方庫,使用方便;但閒暇之餘不妨思考其背後的原理。其實只要不是硬體層面的限制,大多數動效都能在系統 UI 的基礎上自行打造。
下拉刷新:在 scrollViewWillBeginDecelerating 中判斷偏移量,當使用者把列表往下拉超過一定距離時,透過動畫調整 contentInset 騰出空間,並在動畫完成後發起網路請求刷新資料。
上拉載入:關鍵在於 contentOffset.y、contentSize.height 與螢幕高度之間的關係。scrollView 初始並無偏移量,但 contentSize.height 永遠比 contentOffset.y 多出約一個螢幕的高度;當使用者滑到底並再往上拉時,產生的偏移量會讓「偏移量加上螢幕高度」大於內容總高度,此刻即可觸發載入更多資料,並在完成後把 contentInset 歸零。
// 下拉刷新原理
- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView {
if (scrollView.contentOffset.y < -100) {
[UIView animateWithDuration:1.0 animations:^{
self.tableView.contentInset = UIEdgeInsetsMake(150.0f, 0.0f, 0.0f, 0.0f);
} completion:^(BOOL finished) {
// 在此發起網路請求,刷新資料
}];
}
}
// 上拉載入原理
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
if (scrollView.contentOffset.y + scrollView.frame.size.height >= scrollView.contentSize.height) {
[UIView animateWithDuration:1.0 animations:^{
self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 60, 0);
} completion:^(BOOL finished) {
// 發起網路請求,載入更多資料;回來後將 contentInset 改回 (0,0,0,0)
}];
}
}