这个感受写的很好 收藏一下 以备后用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