iOS中如何优化Cell中图片的下载性能
在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];
}
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];
}
(1)其中在加載圖片過程中首先判斷圖片是否已經下載過,如果下載過直接加載,如果沒有下載過那么就需要下載,并且需要填寫一個默認的圖片
其中判斷圖片是否已經下載過是使用字典查詢的
- (NSMutableDictionary *)images {
if (!_images) {
_images = [[NSMutableDictionary alloc]init];
}
return _images;
}
下載圖片,是需要創建一個線程來執行下載,首先應該判斷是否下載線程已經執行,如果執行,不需要重復下載,因此這個線程也是與一個imageURL來綁定
(void)download:(NSString )imageUrl indexPath:(NSIndexPath )indexPath {
[[NSOperationQueue mainQueue] addOperationWithBlock:^{if (image) {appsVc.images[imageUrl] = image;}[appsVc.operations removeObjectForKey:imageUrl];[appsVc.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone]; }];
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];}];
[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];
}
總結
以上是生活随笔為你收集整理的iOS中如何优化Cell中图片的下载性能的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 民生银行信用卡还款日可以改吗?可以还款日
- 下一篇: 【Yoshua Bengio 亲自解答】