這個感受寫的很好 收藏一下 以備後用html
轉自 http://www.cnblogs.com/pengyingh/articles/2354714.htmlios
在iOS應用中,UITableView應該是使用率最高的視圖之一了。iPod、時鐘、日曆、備忘錄、Mail、天氣、照片、電話、短信、Safari、App Store、iTunes、Game Center⋯幾乎全部自帶的應用中都能看到它的身影,可見它的重要性。
然而在使用第三方應用時,卻常常遇到性能上的問題,廣泛表如今滾動時比較卡,特別是table cell中包含圖片的狀況時。
實際上只要針對性地優化一下,這種問題就不會有了。有興趣的能夠看看LazyTableImages這個官方的例子程序,雖然也要從網上下載圖片並顯示,但滾動時絲絕不卡。
下面就說說我對UITableView的瞭解。不過因爲我也是初學者,或許會說錯或遺漏一些,所以僅供參考。
首先說下UITableView的原理。有興趣的能夠看看《About Table Views in iOS-Based Applications》。
UITableView是UIScrollView的子類,所以它能夠自動響應滾動事件(通常爲上下滾動)。
它內部包含0到多個UITableViewCell對象,每一個table cell展現各自的內容。當新cell須要被顯示時,就會調用tableView:cellForRowAtIndexPath:方法來獲取或建立一個cell;而不可視時,它又會被釋放。因而可知,同一時間其實只須要存在一屏幕的cell對象便可,不須要爲每一行建立一個cell。
此外,UITableView還能夠分爲多個sections,每一個區段均可以有本身的head、foot和cells。而在定位一個cell時,就須要2個字段了:在哪一個section,以及在這個section的第幾行。這在iOS SDK中是用NSIndexPath來表述的,UIKit爲其添加了indexPathForRow:inSection:這個建立方法。
其餘諸如編輯之類的就不提了,由於和本文無關。
介紹完原理,接下來就開始優化吧。
緩存
static NSString *CellIdentifier = @"xxx";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
- (void)drawRect:(CGRect)rect {
if (image) {
[image drawAtPoint:imagePoint];
self.image = nil;
} else {
[placeHolder drawAtPoint:imagePoint];
}
[text drawInRect:textRect withFont:font lineBreakMode:UILineBreakModeTailTruncation];
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
if (!decelerate) {
queue.maxConcurrentOperationCount = 5;
}
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
queue.maxConcurrentOperationCount = 5;
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
queue.maxConcurrentOperationCount = 2;
}
此外,自動載入更新數據對用戶來講也很友好,這減小了用戶等待下載的時間。例如每次載入50條信息,那就能夠在滾動到倒數第10條之內時,加載更多信息:網絡
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
if (count - indexPath.row < 10 && !updating) {
updating = YES;
[self update];
}
}
// update方法獲取到結果後,設置updating爲NO
還有一點要注意的就是當圖片下載完成後,若是cell是可見的,還須要更新圖像:多線程
NSArray *indexPaths = [self.tableView indexPathsForVisibleRows];
for (NSIndexPath *visibleIndexPath in indexPaths) {
if (indexPath == visibleIndexPath) {
MyTableViewCell *cell = (MyTableViewCell *)[self.tableView cellForRowAtIndexPath:indexPath];
cell.image = image;
[cell setNeedsDisplayInRect:imageRect];
break;
}
}
// 也可不遍歷,直接與頭尾相比較,看是否在中間便可。
就說那麼多吧,我想作到這些也就差很少了,其餘就須要自行profile,找出瓶頸來優化了。app