Swift闭包中GCD的弱引用问题

3
    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)

错误

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

当编译上述代码时会出现错误,但如果我去掉第二个 [weak self],错误就消失了。
    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)

我认为由于有两个闭包,应该是2个[weak self],但是为什么会出现编译错误,有人知道吗?
1个回答

1
你不需要像在Objective-C中使用@weakify__weak self模式那样在嵌套闭包中重复使用[weak self]
在Swift中,[weak self]由编译器自动创建相同的模式,并且外部闭包定义的弱引用是由内部闭包使用的。
以下是Objective-C版本的相关问题: iOS blocks and strong/weak references to self

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接