So consider this case, i have a UIViewController that contains a simple UICollectionView, but the Delegate & DataSource protocols are separated NSObject's from the UIViewController.
It looks something like this
class MainCollctionViewDelegate: NSObject, UICollectionViewDelegate
class MainCollectionViewDataSrouce: NSObject, UICollectionViewDataSource
And i use them inside my UIViewController like this,
lazy var CVDelegate = MainCollctionViewDelegate()
lazy var CVDataSource = MainCollectionViewDataSrouce()
//MARK: - Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
collectionView.registerCell(PlainCell.self) // register custom cell Nib into collection View.
collectionView.delegate = CVDelegate //Set Deleagte
collectionView.dataSource = CVDataSource // Set data Source
}
Is this approach going to cause any memory leaks in the future ? considering i will implement an injection to fill the data source of the CollectionView to be something like this in the future.
MainCollectionViewDataSrouce(with: Foo) // Foo is some data to populate the collection with.
Is there a better practice to this ? considering I'am trying to achieve the minimum code writing (redundancy).
Note: this also applies for
UITableViewDelegate&UITableViewDataSource
Not right now.
Your memory graph will look like:

So here no memory cycles and no reasons to leak memory.
Important. If you add reference from DataSource / Delegate on your viewController, make sure it is weak reference, otherwise you will create memory cycle.
Note. You can add strong references from DataSource / Delegate on collectionView, since collectionView have weak references on dataSource and delegate. So no cycle as well
Better to register cells in data source, since "only" data source know what types of cell will be used.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With