Hy guys,
我有这些源代码
let downloadTask = session.downloadTaskWithURL(url,
completionHandler: {
[weak button] url, response, error in
if error == nil && url != nil {
if let data = NSData(contentsOfURL: url) {
if let image = UIImage(data: data) {
dispatch_async(dispatch_get_main_queue()) {
if let button = button {
button.setImage(image, forState: .Normal)
}
}
}
}
这段代码尝试将来自url的图像放在button元素中。 有人可以帮我理解为什么在这个源代码块中,在completionHandler参数列表中它使用[弱按钮]? 什么是[弱...]的含义以及为什么要使用它? (我想避免保留周期。) 谢谢你们!
答案 0 :(得分:0)
它不是一个参数,只是声明函数中每次调用按钮都是对按钮的弱引用。 这是一种使用对闭包内对象的弱引用的快捷方法。
这相当于Objective-C:
UIButton * __weak button = ...
答案 1 :(得分:0)
[weak button]
表示按钮参数是可选的,执行完成处理程序时可以为nil。因此有可能按钮不存在于完成块中。您也可以使用[unowned button]
,但只有当您确定该按钮存在时才会使用,否则它将会崩溃。第三个选项是你不要在按钮之前使用neithor weak或者unowned,这意味着在执行闭包之前,它将保持对按钮的强引用,并且不会让它被删除。