Sam*_*Sam 94
要防止块保持对对象的强引用,必须为块定义捕获列表.
闭包表达式语法定义如下:
{ ( /*parameters*/ ) -> /*return type*/ in
// statements
}
Run Code Online (Sandbox Code Playgroud)
但是稍后会在文档中扩展它以包含捕获列表.这有效地等同于表达式语法定义如下:
{ [ /*reference type*/ /*object*/, ... ] ( /*parameters*/ ) -> /*return type*/ in
// statements
}
Run Code Online (Sandbox Code Playgroud)
......哪里/*reference type*/可以是weak或unowned.
捕获列表是第一个出现在闭包中的东西,它是可选的.如上所示,语法被定义为一对或多对引用类型,后跟object; 每对用逗号分隔.例如:
[unowned self, weak otherObject]
Run Code Online (Sandbox Code Playgroud)
完整的例子:
var myClosure = {
[unowned self] in
print(self.description)
}
Run Code Online (Sandbox Code Playgroud)
请注意,unowned引用是非可选的,因此您无需打开它.
希望能回答你的问题.您可以在文档的相关部分中阅读有关Swift中ARC的更多信息.
你应该特别注意weak和之间的区别unowned.在您的实现中使用它可能更安全weak,因为使用unowned假定对象永远不会为零.如果在关闭中使用对象之前实际已取消分配,则可能导致应用程序崩溃.
使用weak作为引用类型,您应该打开?,如下所示:
var myClosure = {
[weak self] in
print(self?.description)
}
Run Code Online (Sandbox Code Playgroud)
如上所述有以下两种方式,以避免保留在夫特周期和这些weak和unowned如下所述:
var sampleClosure = { [unowned self] in
self.doSomething()
}
Run Code Online (Sandbox Code Playgroud)
其中,self永远不能nil.
var sampleClosure = { [weak self] in
self?.doSomething()
}
Run Code Online (Sandbox Code Playgroud)
哪里self需要打开使用?.这里有一个重要的观察要做,如果有更多的指令使用self并且可以分享结果等,可能的正确方法可以是:
var sampleClosure = { [weak self] in
if let this = self{
this.doSomething()
this.doOtherThings()
}
}
Run Code Online (Sandbox Code Playgroud)
要么
var sampleClosure = { [weak self] in
guard let strongSelf = self else{
return
}
strongSelf.doSomething()
strongSelf.doOtherThings()
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18887 次 |
| 最近记录: |