简体   繁体   English

使用 UITableView 关闭捕获内存泄漏问题

[英]Closure Capture Memory Leak issue with UITableView

In willDisplay method, I get UIImage and IndexPath from a callback closure.willDisplay方法中,我从回调闭包中获取UIImageIndexPath I am using tableView inside that closure.我在那个闭包中使用tableView Should I need to make that tableView weak to avoid possible memory leaks, or is it not an issue to use strong tableView ?我应该让 tableView 变weak以避免可能的内存泄漏,还是使用strong tableView不是问题?

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    guard let cell = cell as? ArtistTableViewCell else { return }
    guard let imageUrl = cell.viewModel.artistImage() else { return }

    // Download image callback closure returns UIImage, IndexPath, and error
    ImageDownloadService.shared.downloadImage(imageUrl,indexPath:indexPath) { [weak tableView] (image, index, error) in
        DispatchQueue.main.async {
            guard let getIndexPath = index else { return }
            guard let getImage = image else { return }
            guard let getCell = tableView?.cellForRow(at: getIndexPath) as? ArtistTableViewCell else { return }

            getCell.setArtistImage(getImage)
        }
    }
}

It's not necessary to capture tableView explicitly because it's provided as local variable in the first parameter of the willDisplay method.没有必要显式捕获tableView因为它在willDisplay方法的第一个参数中作为局部变量提供。

Therefore it will not cause a memory leak.因此它不会导致内存泄漏。

There is a simple rule: Don't capture anything which is locally accessible inside the method.有一个简单的规则:不要捕获方法内部可本地访问的任何内容。

Feel free to prove it with Instruments.随意用 Instruments 来证明它。

语言环境变量不会被闭包捕获,因为它们在同一范围内,因此您无需将 tableview 设为弱引用。

weak is preferred. weak优先。 If you retain the tableView and dismiss the view controller while it downloads an image the table view object (and its cells) won't be deallocated until the call download finishes.如果在下载图像时保留tableView并关闭视图控制器,则在调用下载完成之前,不会释放表视图对象(及其单元格)。 (however no retain cycle will occur) (但是不会发生保留循环)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM