1

Edit: I checked the similar question, but that's passing self:

var buttonAction: ((UITableViewCell) -> Void)?

@IBAction func buttonPressed(_ sender: Any) {
     buttonAction?(self)
}

While I'm no passing anything


I have a UICollectionView full of cells that contain UITextFields. This is what my cell looks like:

class SearchCell: UICollectionViewCell {
    @IBOutlet weak var textField: UITextField!
    var startedEditing: (() -> Void)?
    var endedEditing: (() -> Void)?
}
extension SearchCell: UITextFieldDelegate {
    func textFieldDidBeginEditing(_ textField: UITextField) {
        startedEditing?()
    }
    func textFieldDidEndEditing(_ textField: UITextField, reason: UITextField.DidEndEditingReason) {
        endedEditing?()
    }
}

I'm assigning the UITextField delegate to SearchCell. Whenever a delegate function is called, I call a closure.

I then add a print statement to the closure inside collectionView(_:cellForItemAt:):

extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionCell", for: indexPath) as? SearchCell {
            cell.startedEditing = { [weak self] in /// do I need weak self here?
                print("\(indexPath) started editing")
            }
            cell.endedEditing = { [weak self] in /// or here?
                print("\(indexPath) ended editing")
            }
        }
    }
}

My question is, do I need [weak self] inside the closure? Currently, I'm not even referencing self (I just get the indexPath), and Xcode says "Variable 'self' was written to, but never read." But, isn't the flow currently collectionView(_:cellForItemAt:)SearchCellcollectionView(_:cellForItemAt:) -- which seems like it captures something...

Should it be [weak collectionView]? Or, if I change it to:

cell.startedEditing = { [weak self] in
    print("\(indexPath) started editing")
    self?.callSomeFunction()
}

Is [weak self] appropriate there?

Thanks in advance!

aheze
  • 24,434
  • 8
  • 68
  • 125
  • 1
    Yes , you would need [weak self] . If you don't use it, self i.e ViewController will be retained by the SearchCell. You can try to find this out, launch your app and open "Debug Memory Graph". Select ViewController you will see, SearchCell does not hold a reference to it when using weak self . Now try removing weak self and you will see all the Search cell's being displayed will hold reference of your ViewController, it might cause leak at some point. So if the closure is called immediately you don't need but if the closure it to be called at some later point you need it. – NNikN Oct 10 '20 at 20:41
  • @NNikN Got it, thanks! – aheze Oct 10 '20 at 21:01

0 Answers0