How to get rid of retain cycle with collectionview
Asked Answered
H

1

1

I am having trouble destroying viewcontrollers due what I believe to be a retain cycle between a collectionview and the viewcontroller. I tried making the collectionview a weak variable but I am now getting nil whenever I trying to add the collectionview to the viewcontroller. If there is another route to try rather than making the collectionview weak I'm open to that as well.

weak var table = UICollectionView(frame: CGRect(x: 0, y: 0, width: 0, height: 0), collectionViewLayout: UICollectionViewFlowLayout())
weak var customFlowLayout = UICollectionViewFlowLayout() //default cell spacing is 10





table?.frame = CGRect(x: 0, y: 50, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
table?.isHidden = true
table?.backgroundColor = UIColor.white
table?.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "customCellIdentifier")
table?.dataSource = self
table?.delegate = self
//table.rowHeight = CGFloat(100)
customFlowLayout?.minimumLineSpacing = 5 //default is 10
table?.collectionViewLayout = customFlowLayout!
self.view.addSubview(table!)  //this is the line that breaks every time
Hermit answered 2/11, 2017 at 19:57 Comment(2)
How are you trying to destroy ViewControllers?Filmore
Collection view should not be a problem. Problem is when you hold the direct reference to the view controller, then the view controller cannot be deinited. I bet you do that somewhere.Decca
I
4

I don't see any retain cycles from the code you provided. Unless there is a block being passed somewhere, it's likely pretty difficult to have a retain cycle directly caused by a standard UICollectionView. If anything it's likely that your view controller holding onto the UICollectionView is never being released.

The property on your view controller for the UICollectionView can be weak, but you need to declare the local variable as a strong reference (no weak) like so:

class ViewController : UIViewController {
    weak var collectionView: UICollectionView?

    // Maybe in viewDidLoad()    
    let cv = UICollectionView(...)
    ...
    self.view.addSubview(cv)
    self.collectionView = cv

Your local declaration should be a strong reference, otherwise it will be allocated and immediately released because nothing is holding onto it. Once cv is added as a subview, then it will have a strong reference from the view. Your class's property called collectionView can now be a weak reference and the collectionView will be released once the view is deallocated.

Indubitable answered 2/11, 2017 at 20:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.