Search code examples
iosswiftretain-cycle

iOS Swift 3: does retain cycle happens in this case?


func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "CheckoutCell") as! CheckoutCell

    let product = shoppingCart[indexPath.row]

    var tfQuantity : UITextField!
    cell.clickEditAction = { [weak self] celll in
        guard let ss = self else { return }
        let alert = UIAlertController(title: nil, message: "Enter new quantity", preferredStyle: .alert)

        alert.addTextField { (textfield) in
            tfQuantity = textfield
        }

        let okAction = UIAlertAction(title: "OK", style: .default) { (action) in
            if tfQuantity.text == ""{
                return
            }

            if let newQuantity = Int(tfQuantity.text){
                product.quantity = newQuantity
                self.tbvCheckout.reloadData()
            }
            return
        }

        alert.addAction(okAction)
        self.present(alert, animated: true, completion: nil)
    }

    return cell
}

This line of code:

self.tbvCheckout.reloadData()

If I don't use [weak self] or [unowned self], does it create retain cycle between current object & UIAlertAction instance? What if I use this code instead: tableView.reloadData()?


Solution

  • Couple of things:

    First, You have created a weak reference, but I don't see you using it in the code.

    guard let ss = self else { return }
    

    Any reference to self should be via this weak self variable "ss" that you have created.

    Second, The alert action block should also have weak reference to self

    let okAction = UIAlertAction(title: "OK", style: .default) { [weak self] (action) in
            if tfQuantity.text == ""{
                return
            }
    
            if let newQuantity = Int(tfQuantity.text){
                product.quantity = newQuantity
                self?.tbvCheckout.reloadData()
            }
            return
        }