我有这个代码,我正在质疑我是否需要使用捕获列表来引用self弱.
现在我正在考虑getTextFileData并且.main.async是静态方法,因此,这不会导致保留周期.但是,我确实访问了该games物业,有点不确定.
NPWebService.getTextFileData { (games, success) in
if success {
self.games = games
DispatchQueue.main.async {
self.updateUI()
}
}
}
Run Code Online (Sandbox Code Playgroud)
这不会导致保留周期,因为它看起来像是不同类型的静态方法.因此,该getTextFileData方法将暂时保留您传入的闭包,直到任何异步工作完成,并且闭包将暂时保留self.但是当工作完成并且关闭完成后,这些临时保留将到期,并且自动内存管理可以适当地清理.
保留周期的危险在于你有一个引用/捕获self的闭包,而self也保留了闭包.像这样:
class GameController {
var games: [Game]?
// self retains the closure as a property
let updateClosure:([Game], Bool)->() = {
games, success in
if success {
self.games = games // and the closure captures self. Each retains each other indefinitely, this is a retain cycle and neither this closure nor self will ever be deallocated
}
}
func load() {
NPWebService.getTextFileData(updateClosure)
}
}
Run Code Online (Sandbox Code Playgroud)
因此,通常只需要关闭捕获列表中的弱自我或无主自我: