在iOS開發中使用最為常見的是UITableView,其中UITabelViewCell中下載圖片,會影響用戶下拉刷新UI,導致卡頓,用戶體驗不好,在這篇blog中,我將以一個例子來說明如何優化UITableView下載圖片
1.使用懶加載方式,首先將CellData數據加載進來
// lazy
- (NSMutableArray*)apps {
if (!_apps) {
NSString *path = [[NSBundle mainBundle]pathForResource:@”apps.plist” ofType:nil];
NSArray *dictArray = [NSArray arrayWithContentsOfFile:path];
NSMutableArray *appArray = [NSMutableArray array];for (NSDictionary *dict in dictArray) {App *app = [App appWithDict:dict];[appArray addObject:app];}_apps = appArray;
}
return _apps;
}
2.然后在UITaleView的dataSource方法中加載數據
//Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.apps.count;
}
- (UITableViewCell )tableView:(UITableView )tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *ID = @”app”;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID forIndexPath:indexPath];
if (!cell) {cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
}
App *app = self.apps[indexPath.row];
cell.textLabel.text = app.name;
cell.detailTextLabel.text = app.download;UIImage *image = self.images[app.icon];
if (image) {cell.imageView.image = image;
} else {cell.imageView.image = [UIImage imageNamed:@"placeholder"];// 下載圖片[self download:app.icon indexPath:indexPath];
}return cell;
}
(1)其中在加載圖片過程中首先判斷圖片是否已經下載過,如果下載過直接加載,如果沒有下載過那么就需要下載,并且需要填寫一個默認的圖片
其中判斷圖片是否已經下載過是使用字典查詢的
- (NSMutableDictionary *)images {
if (!_images) {
_images = [[NSMutableDictionary alloc]init];
}
return _images;
}
下載圖片,是需要創建一個線程來執行下載,首先應該判斷是否下載線程已經執行,如果執行,不需要重復下載,因此這個線程也是與一個imageURL來綁定
(void)download:(NSString )imageUrl indexPath:(NSIndexPath )indexPath {
NSBlockOperation *operation = self.operations[imageUrl];
// 如果存在操作則直接返回,防止已經在下載的操作重復下載
if (operation) {
return;
}
__weak typeof (self) appsVc = self;
operation = [NSBlockOperation blockOperationWithBlock:^{
NSURL *url = [NSURL URLWithString:imageUrl];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];[[NSOperationQueue mainQueue] addOperationWithBlock:^{if (image) {appsVc.images[imageUrl] = image;}[appsVc.operations removeObjectForKey:imageUrl];[appsVc.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone]; }];
}];
[self.queue addOperation:operation];self.operations[imageUrl] = operation;
}
為進一步優化,應在用戶滑動過程中停止下載,結束拖拽時候開始下載
/**
* 當用戶開始拖拽表格時調用
*/
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
// 暫停下載
[self.queue setSuspended:YES];
}
/**
* 當用戶停止拖拽表格時調用
*/
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
// 恢復下載
[self.queue setSuspended:NO];
}