简体   繁体   中英

Is this the correct place to use weak self in closure?

I have a viewController that has a collectionView outlet. In the cellForRowAt method I call this code:

guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "photoCell", for: indexPath) as? MediaPhotoCell else {fatalError("Could not initialize cell")}
       cell.configureForMedia(obj, completion: { [weak self](image:UIImage?) in
            if let loadedImage = image {
                    let photo = self?.loadedPhotos[indexPath.row]
                    photo?.image = loadedImage
                    self?.loadedPhotos[indexPath.row] = photo
                    self?.photosViewController?.updateImage(for: photo)
                }
            })
return cell

I've been spending time on learning how to resolve/prevent memory leaks through retain cycles. I added a capture list [weak self] before capturing the value in the closure (image: UIIimage?). My logic is that since viewController owns the collectionview, and that collectionview owns the cell, which has a closure method in it's custom implementation (custom cell), and closure references self, i'm creating a retain cycle if i do not declare self as weak.

Is this necessary? Or is this not necessary if the outlet (the collectionView) is declared as weak?

Your example works to create a weak reference to self for use in a closure.

As to @IanMacDonald comment about it not being required for your example, he is also correct. So you would only need to do this if self could be nil in the closure.

A good example case for using [weak self] would be for an asynchronous network request, in a view controller where that request is used to populate the view. If the user backs out, we no longer need to populate the view, nor do we need a reference to the view controller.

I really liked this medium article about reference counting in closures.

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