我的应用程序使用CoreData
作为持久性数据存储。下面是我的tableview代码。在模拟器上它运行良好,但在手机上运行它时会非常迟钝。任何关于优化的建议都赞赏:)
-(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;
}
由于此API使用,您遇到了低FPS
滞后:
[UIImage imageWithData:journal.image]
UIImage
imageWithData:
方法不是异步的,因此当表视图加载每个新单元时,它必须处理数据,同时锁定应用程序。
尝试找到在后台线程上加载/创建/缓存图像的异步方式,使您的UI响应。 查看这个流行的图像加载/缓存库SDWebImage,以获得更多的想法/灵感和潜在的解决方案,满足您的需求。
首先,您可以自定义单元格,有些代码是不必要的,例如每次都设置Font和TextColor。接下来,您可以使用instrument - > Profile查找耗时的代码。希望它可以帮到你!