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


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 }

任何对自我的引用都应该通过你创建的这个弱自我变量"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
    }

最新更新