简体   繁体   中英

Closure Capture Memory Leak issue with UITableView

In willDisplay method, I get UIImage and IndexPath from a callback closure. I am using tableView inside that closure. Should I need to make that tableView weak to avoid possible memory leaks, or is it not an issue to use 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.

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.

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

weak is preferred. 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. (however no retain cycle will occur)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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