繁体   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
}

这行代码:

self.tbvCheckout.reloadData()

如果我不使用[弱自我]或[无名自我],是否会在当前对象和UIAlertAction实例之间创建保留周期? 如果我改用以下代码怎么办:tableView.reloadData()?

几件事情:

首先,您创建了一个弱引用,但是我看不到您在代码中使用它。

guard let ss = self else { return }

对self的任何引用都应该通过您创建的这个弱的self变量“ ss”进行。

其次,警报动作块还应该弱引用自己

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