swift 闭包中 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)
错误
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],谁知道为什么会出现编译错误
您不必像 Objective-C.
中的 @weakify
或 __weak self
模式一样在嵌套闭包中重复 [weak self]
[weak self]
in Swift 编译器自动创建相同的模式,weak self 由外层闭包定义,内层闭包使用。
Objective-C版本对应的问题如下:
iOS blocks and strong/weak references to self
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],谁知道为什么会出现编译错误
您不必像 Objective-C.
中的@weakify
或 __weak self
模式一样在嵌套闭包中重复 [weak self]
[weak self]
in Swift 编译器自动创建相同的模式,weak self 由外层闭包定义,内层闭包使用。
Objective-C版本对应的问题如下: iOS blocks and strong/weak references to self