How to get rid of retain cycle with collectionview

為{幸葍}努か 提交于 2020-06-13 09:18:15

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/47083638/how-to-get-rid-of-retain-cycle-with-collectionview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!