这个感觉写的很好 收藏一下 以备后用
转自 http://www.cnblogs.com/pengyingh/articles/2354714.html
在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,找出瓶颈来优化了。
uitableview性能优化(转),布布扣,bubuko.com
原文:http://www.cnblogs.com/huanglong/p/3585304.html