【问题标题】:weak self in gcd in swift closure快速关闭时gcd中的弱自我
【发布时间】:2015-02-28 10:37:21
【问题描述】:
    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 个闭包,应该是 2 个 [weak self],任何人都知道为什么会发生编译错误

【问题讨论】:

    标签: swift closures grand-central-dispatch weak-references


    【解决方案1】:

    您不必像 Objective-C 中的 @weakify__weak self 模式一样在嵌套闭包中重复 [weak self]

    [weak self]在Swift中由编译器自动创建相同的模式,弱self由外部闭包定义为内部闭包使用。

    Objective-C 版本对应的问题如下: iOS blocks and strong/weak references to self

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-06
      • 1970-01-01
      • 2011-07-29
      • 1970-01-01
      • 2016-11-09
      • 1970-01-01
      相关资源
      最近更新 更多