【发布时间】:2016-12-10 06:59:10
【问题描述】:
@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)
}
我有这个回调地狱,我想知道
回调地狱最顶端的
[weak self]和guard let strongSelf是否通过GCD 的异步回调完全阻止了强引用循环。我在这里读到了其他帖子,也是一本书的帖子,上面说如果我在回调中引用的对象可以deinit成功,这意味着没有强引用周期的好兆头,这仍然是真的吗?如何防止这种回调地狱,你能引导我一些我错过的阅读材料或主题吗?类似于 javascript 的承诺链语法?
【问题讨论】:
标签: ios swift multithreading swift3 grand-central-dispatch