简体   繁体   English

iOS Swift 3:在这种情况下会发生保留周期吗?

[英]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? 如果我不使用[弱自我]或[无名自我],是否会在当前对象和UIAlertAction实例之间创建保留周期? What if I use this code instead: tableView.reloadData()? 如果我改用以下代码怎么办:tableView.reloadData()?

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. 对self的任何引用都应该通过您创建的这个弱的self变量“ ss”进行。

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
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM