在Swift中阻止保留周期?

Adr*_*ian 50 swift

传统上在Objc中,我们使用weakSelf来防止块的额外保留计数.

swift内部如何管理Objc块中发生的保留周期?

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*/可以是weakunowned.

捕获列表是第一个出现在闭包中的东西,它是可选的.如上所示,语法被定义为一对或多对引用类型,后跟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)

  • 克里斯,我认为Sam意味着在Swift中使用`println(self?.description)`这称为[可选链接](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/OptionalChaining .html)另外作为进一步说明,'println`在Swift 2中已被弃用,而不是'print` (2认同)

Ten*_*Jay 13

唯一让我离开捕获列表的是什么时候使用弱vs无主.

这本书将其简化为以下规则:

如果封闭使用自我可能是零[弱自我].

如果自我永远不会在闭包中使用[无主自我].

请参见弱和无主引用雨燕编程语言的书进行更深层次的解释.


cic*_*ska 6

如上所述有以下两种方式,以避免保留在夫特周期和这些weakunowned如下所述:

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)