Swift 闭包语法中的 weakSelf
Swift weakSelf in closure syntax
我有这个代码可以获取 JSON:
Alamofire.request(.GET, worlds).responseJSON { (request, response, JSON, error) in
println(JSON)
//weakSelf.serverList = JSON
}
这里如何声明weakSelf?我知道在我的情况下它应该是无主的,但我找不到正确的语法。当我尝试使用 [unowned self].serverList 而不是注释行时,编译器显示错误 "use of unresolved identifier 'unowned'"。
我也试过像这样在块之前声明常量:
unowned let uSelf = self
它就像一个魅力,但我想了解如何在我的案例中使用 [unowned self]。
您可以通过在闭包参数前放置 [weak self]
来声明弱自引用。
您可以看到 documentation here
使用捕获列表。正确的语法是:
Alamofire.request(.GET, worlds).responseJSON { [unowned self] (request, response, JSON, error) in
println(JSON)
self.serverList = JSON
}
但是请注意,您没有在此处创建保留循环,因此您不必在此处使用 weak
或 unowned
self。关于这个主题的好文章:http://digitalleaves.com/blog/2015/05/demystifying-retain-cycles-in-arc/
我有这个代码可以获取 JSON:
Alamofire.request(.GET, worlds).responseJSON { (request, response, JSON, error) in
println(JSON)
//weakSelf.serverList = JSON
}
这里如何声明weakSelf?我知道在我的情况下它应该是无主的,但我找不到正确的语法。当我尝试使用 [unowned self].serverList 而不是注释行时,编译器显示错误 "use of unresolved identifier 'unowned'"。 我也试过像这样在块之前声明常量:
unowned let uSelf = self
它就像一个魅力,但我想了解如何在我的案例中使用 [unowned self]。
您可以通过在闭包参数前放置 [weak self]
来声明弱自引用。
您可以看到 documentation here
使用捕获列表。正确的语法是:
Alamofire.request(.GET, worlds).responseJSON { [unowned self] (request, response, JSON, error) in
println(JSON)
self.serverList = JSON
}
但是请注意,您没有在此处创建保留循环,因此您不必在此处使用 weak
或 unowned
self。关于这个主题的好文章:http://digitalleaves.com/blog/2015/05/demystifying-retain-cycles-in-arc/