如何使用CollectionView摆脱保留周期 [英] How to get rid of retain cycle with collectionview
问题描述
由于我认为这是collectionview和viewcontroller之间的保留周期,因此我在销毁viewcontroller时遇到了麻烦.我试图使collectionview成为一个弱变量,但是当我尝试将collectionview添加到viewcontroller时,我现在得到的是nil.如果还有另一种方法可以尝试而不是使collectionview变弱,那么我也对此持开放态度.
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
推荐答案
我看不到您提供的代码中的任何保留周期.除非某个地方传递了一个块,否则很难有一个由标准UICollectionView
直接引起的保留周期.如果有的话,挂在UICollectionView
上的视图控制器可能永远不会释放.
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.
UICollectionView
的视图控制器上的属性可能很弱,但是您需要像这样声明局部变量作为强引用(没有weak
):
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
您的本地声明应作为强引用,否则将被分配并立即释放,因为没有任何保留.将cv
添加为子视图后,它将具有来自view
的强大引用.您班级的名为collectionView
的属性现在可以作为弱引用,并且在取消分配视图后将释放collectionView
.
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.
这篇关于如何使用CollectionView摆脱保留周期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!