简体   繁体   English

关闭语法中的Swift weakSelf

[英]Swift weakSelf in closure syntax

I have this code to get JSON: 我有这个代码来获取JSON:

Alamofire.request(.GET, worlds).responseJSON { (request, response, JSON, error) in
        println(JSON)
        //weakSelf.serverList = JSON
    }

How to declare weakSelf here? 如何在这里申报weakSelf? I know it should be unowned in my case, but I can't find correct syntax for this. 我知道在我的情况下它应该是无主的,但我找不到正确的语法。 When I try use [unowned self].serverList instead of the commented line, the compiler shows me error "use of unresolved identifier 'unowned'". 当我尝试使用[unowned self] .serverList而不是注释行时,编译器显示错误“使用未解析的标识符'unowned'”。 I also tried to declare constant before block like this: 我也尝试在块之前声明常量,如下所示:

unowned let uSelf = self

It works like a charm, but I want to understand how to use [unowned self] in my case. 它就像一个魅力,但我想了解如何在我的情况下使用[无主自我]。

Use the capture list. 使用捕获列表。 The correct syntax is: 正确的语法是:

Alamofire.request(.GET, worlds).responseJSON { [unowned self] (request, response, JSON, error) in
    println(JSON)
    self.serverList = JSON
}

However take a note that you are not creating retain cycle here, so you do not have to use weak or unowned self here. 但请记住,您不是在这里创建保留周期,因此您不必在此处使用weakunowned Good article on this topic: http://digitalleaves.com/blog/2015/05/demystifying-retain-cycles-in-arc/ 关于这个主题的好文章: http//digitalleaves.com/blog/2015/05/demystifying-retain-cycles-in-arc/

You can declare a weak self reference by putting [weak self] before your closure parameters. 您可以通过在闭包参数之前放置[weak self]来声明弱自引用。

You can see the documentation here 您可以在此处查看文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM