【问题标题】:App Crashes when too many images are in TableView当 TableView 中的图像过多时应用程序崩溃
【发布时间】:2016-10-27 18:16:17
【问题描述】:

我有一个表格,我用 Runner Objects 中存储的信息填充该表格。每个 Runner 对象都有一个名为 fileName 的属性,该属性对应于保存在文档目录中的图像。

如果我从一张空桌子开始,我可以添加跑步者和他们的照片,直到我达到大约 8 名跑步者。当我尝试为第 8 位左右的跑步者添加照片时,应用程序崩溃了。这似乎是一个内存问题,但是当我在本地存储的所有内容都是对目录中图像的 references 时,我不明白这是怎么回事。

我将一个 runner 对象传递给我的 RunnerCell 类中的设置单元格方法,并像这样设置单元格:

if (currentRunner.fileName != nil) {
    if ([manager fileExistsAtPath:fullPath]){

        UIImage *originalImage = [[UIImage alloc] initWithContentsOfFile:fullPath];

        if ([currentRunner.photoOrientation isEqual: @"portrait"]) {
                CGImageRef imageRef = [originalImage CGImage];
                UIImage *rotatedImage = [UIImage imageWithCGImage:imageRef scale:1.0 orientation:UIImageOrientationRight];
            self.runnerImageView.image = rotatedImage;
        } else {
            self.runnerImageView.image = originalImage;
        }
        self.addPhotoLabel.hidden = true;
    }
}

【问题讨论】:

    标签: objective-c image memory directory tableview


    【解决方案1】:

    根据文档规定,您不得将图像加载到主线程上的UITableViewCell。这就是您的应用程序崩溃的原因。 因为当您在主线程上加载图像时,滚动时会变得过于滞后,因为可取消使用的单元格重新分配单元格并再次为即将到来的索引路径的单元格加载图像,直到图像加载它会阻塞主线程,从而导致 tableview 的延迟行为。

    请在后台线程中加载您的缓存图像。使用此代码。

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^(void) {
    
        if ([currentRunner.photoOrientation isEqual: @"portrait"]) {
                CGImageRef imageRef = [originalImage CGImage];
                UIImage *rotatedImage = [UIImage imageWithCGImage:imageRef scale:1.0 orientation:UIImageOrientationRight];
            dispatch_sync(dispatch_get_main_queue(), ^(void) {
            self.runnerImageView.image = rotatedImage;
        });
        } else {
              dispatch_sync(dispatch_get_main_queue(), ^(void) {
            self.runnerImageView.image = originalImage;
        });
        }
    
    });
    

    【讨论】:

    • 谢谢!如果我将此设置移至 willDisplayCell tableView 委托方法,性能会更好吗?
    • 我没试过你可以试试。可能会像你想的那样工作。但根据建议,您应该将其实现到 cellForRowMethod 中。
    猜你喜欢
    • 1970-01-01
    • 2015-04-17
    • 2021-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-25
    • 2016-02-11
    相关资源
    最近更新 更多