简体   繁体   English

快速关闭中gcd的自我弱化

[英]weak self in gcd in swift closure

    apiFunc(user: User.currentUser, start: 0, limit: Constants.numberOfItemInOnePage,
        success: { [weak self] (friends) -> Void in
            dispatch_async(dispatch_get_main_queue(), { [weak self] () -> Void in
                if let strongSelf = self {
                    strongSelf.friendList = friends
                    strongSelf.loading = false
                    strongSelf.tableView.reloadData()
                }
            })
        }, failure: nil)

error 错误

Command /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc failed with exit code 1

happens when compile the code above, but if I remove the 2nd [weak self], error disappears 编译上面的代码时发生,但如果我删除第二个[弱自我],错误消失

    apiFunc(user: User.currentUser, start: 0, limit: Constants.numberOfItemInOnePage,
        success: { [weak self] (friends) -> Void in
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                if let strongSelf = self {
                    strongSelf.friendList = friends
                    strongSelf.loading = false
                    strongSelf.tableView.reloadData()
                }
            })
        }, failure: nil)

I think as there are 2 closures, it should be 2 [weak self], anyone knows why compile error happens 我认为因为有2个闭包,它应该是2 [弱自我],任何人都知道为什么编译错误发生

You don't have to repeat [weak self] in nested closures in the same way as @weakify or __weak self patterns in Objective-C. 您不必在嵌套闭包中重复[weak self] ,就像在Objective-C中使用@weakify__weak self模式一样。

[weak self] in Swift automatically creates the same pattern by the compiler, and the weak self is defined by the outer closure is used by the inner closure. Swift中的[weak self]自动由编译器创建相同的模式,而弱自我由外部闭包定义,由内部闭包使用。

Here is the corresponding question for Objective-C version: iOS blocks and strong/weak references to self 以下是Objective-C版本的相应问题: iOS块和对self的强/弱引用

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

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