嵌套回调强引用循环

时间:2016-12-10 06:59:11

标签: ios swift multithreading swift3 grand-central-dispatch

@IBAction func sendSweet(sender: UIBarButtonItem) {

    var inputTextField: UITextField?
    let alert = UIAlertController(title: "New sweet", message: "Enter a sweet", preferredStyle: .alert)
    alert.addTextField { (textField: UITextField) in
        textField.placeholder = "Your sweet"
        inputTextField = textField
    }

    let sendAction = UIAlertAction(title: "Send", style: .default, handler: {
        [weak self] (alertAction: UIAlertAction) in
        guard let strongSelf = self else { return }

        if inputTextField?.text != "" {
            let newSweet = CKRecord(recordType: "Sweet")
            newSweet["content"] = inputTextField?.text as CKRecordValue?

            let publicData = CKContainer.default().publicCloudDatabase
            publicData.save(newSweet, completionHandler: {
                (record: CKRecord?, error: Error?) in

                if error == nil {
                    // we want ui code to dispatch asychronously in main thread
                    DispatchQueue.main.async {
                        strongSelf.tableView.beginUpdates()
                        strongSelf.sweets.insert(newSweet, at: 0)
                        let indexPath = IndexPath(row: 0, section: 0)
                        strongSelf.tableView.insertRows(at: [indexPath], with: .top)
                        strongSelf.tableView.endUpdates()
                    }
                } else {
                    if let error = error {
                        print(error.localizedDescription)
                        return
                    }
                }
            })
        }
    })

    alert.addAction(sendAction)
    alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
    present(alert, animated: true, completion: nil)

}

我有这个回调地狱,我想知道

  1. [weak self]& guard let strongSelf在回调的最顶端,通过GCD的异步回调阻止强引用循环。我在这里读了一些其他的帖子,也是一本书中的一篇,它说如果我在回调中引用的对象能成功deinit,那就意味着没有强大的参考周期的好迹象,它仍然是真的吗? / p>

  2. 如何防止这种回调地狱,你能引导我读一些我错过的阅读材料或话题吗?像javascript的承诺链接语法?

2 个答案:

答案 0 :(得分:1)

据我所知,没有保留周期,因此无需弱化self。你当然可以在每个街区都做到防守。

没有保留周期,因为实例(self)没有引用任何闭包。特别是sendActionsendAction函数内部声明了sendSweet

class MyView: UIView {
    let str = "some variable to have somsthing to use self with"

    func foo() {
        let ba = {
            // no problem. The instance of MyView (self) does not hold a (strong) reference to ba
            self.str.trimmingCharacters(in: CharacterSet.alphanumerics)
        }

        ba()
    }
}

如果您将let sendAction = ...作为实例的属性移出函数之外,则会有一个引用循环。在这种情况下,实例(self)会强烈引用sendAction,而sendAction闭包会强烈引用该实例(self):

self< - > {self。 ......}又名sendAction

class MyView: UIView {
    let str = "asd"
    // Problem. 
    // The instance of MyView (self) does hold a (strong) reference to ba ...
    let ba: () -> Void 

    override init(frame: CGRect) {
        super.init(frame: frame)
        ba = {     
            // ... while ba holds a strong reference to the instance (self)           
            self.str.trimmingCharacters(in: CharacterSet.alphanumerics)
        }
    }

    func foo() {
        ba()
    }
}

在这种情况下,你必须按照weak打开周期,如果你在关闭时self,就像你一样。

  

如何防止这种回调地狱,你能不能引导我阅读一些阅读材料

结帐DispatchGroup s。

Apple Documentation

答案 1 :(得分:0)

为我的问题#2找到了一个非常巧妙的解决方案

https://github.com/duemunk/Async

示例摘录:

Async.userInitiated {
    return 10
}.background {
    return "Score: \($0)"
}.main {
    label.text = $0
}