iOS Objective C - UITableView 性能问题

Posted

技术标签:

【中文标题】iOS Objective C - UITableView 性能问题【英文标题】:iOS Objective C - UITableView performance issue 【发布时间】:2017-12-22 20:41:55 【问题描述】:

我的应用程序使用CoreData 作为持久性数据存储。下面是我的表格视图代码。在模拟器上它运行良好,但在手机上运行时它变得非常滞后。任何关于优化的建议表示赞赏:)

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 

CustomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
Journal* journal = [self.fetchedResultsController objectAtIndexPath:indexPath];

cell.titleLabel.text = journal.title.uppercaseString;
cell.titleLabel.font = [UIFont fontWithName:@"SourceSansPro-Bold" size:25];
cell.titleLabel.textColor = [UIColor blackColor];

cell.detailLabel.text = journal.detail;
cell.detailLabel.font = [UIFont fontWithName:@"SourceSansPro-SemiBold" size:18];
cell.detailLabel.textColor = [UIColor blackColor];

NSDate *currentDate = journal.timeStamp;

cell.dateLabel.text = [self.dateFormatter stringFromDate: currentDate];
cell.dateLabel.font = [UIFont fontWithName:@"SourceSansPro-SemiBold" size:16];
cell.dateLabel.textColor = [UIColor blackColor];

cell.locationLabel.text = [NSString stringWithFormat:@"%@, %@", journal.city, journal.country];
cell.locationLabel.font = [UIFont fontWithName:@"SourceSansPro-SemiBold" size:18];
cell.locationLabel.textColor = [UIColor blackColor];

cell.tempLabel.text = [NSString stringWithFormat:@"%g°C", round(journal.temp)];
cell.tempLabel.font = [UIFont fontWithName:@"SourceSansPro-SemiBold" size:18];
cell.tempLabel.textColor = [UIColor blackColor];
cell.weatherIcon.image = [UIImage imageNamed:journal.condition];

cell.backgroundView = [[UIImageView alloc] initWithImage:[ [UIImage imageWithData:journal.image] stretchableImageWithLeftCapWidth:0.0 topCapHeight:5.0] ];
cell.backgroundView.contentMode = UIViewContentModeScaleAspectFill;
cell.selectedBackgroundView = [[UIImageView alloc] initWithImage:[ [UIImage imageWithData:journal.image] stretchableImageWithLeftCapWidth:0.0 topCapHeight:5.0] ];
cell.selectedBackgroundView.contentMode = UIViewContentModeScaleAspectFill;
cell.backgroundView.alpha = 0.5;
cell.selectedBackgroundView.alpha = 0.5;

return cell;

【问题讨论】:

如果您想要代码并提高效率,那么这属于Code Review 我建议从使用 Instruments 开始测量滞后部分占用的时间。 【参考方案1】:

由于此 API 的使用,您的 FPS 延迟较低:

[UIImage imageWithData:journal.image]

UIImageimageWithData: 方法不是异步的,因此当表格视图加载每个新单元格时,它必须处理数据,同时锁定应用程序。

尝试找到一种异步方式来在后台线程上加载/创建/缓存图像,从而使您的 UI 具有响应性。 查看这个流行的图像加载/缓存库SDWebImage,了解更多想法/灵感和满足您需求的潜在解决方案。

【讨论】:

【参考方案2】:

首先,您可以自定义一个单元格,一些代码是不必要的,例如每次设置Font和TextColor。 接下来可以使用instrument-->Profile查找耗时的代码。 希望对你有帮助!

【讨论】:

以上是关于iOS Objective C - UITableView 性能问题的主要内容,如果未能解决你的问题,请参考以下文章

将 NSArray 传递给 UITable View 而不是 UILabel [关闭]

Objective C iOS简单图像旋转类

Effective Objective -C 第一章 熟悉iOS

使用 IOS9 时,无法在 UITable 的部分标题上的 UIButtons 上触发触摸事件(IOS10 很好)

Objective-C iOS应用程序中的C风格函数[关闭]

iOS-Objective-C的本质