内存管理/Memory Management
Code (even non-production, tutorial demo code) should not create reference cycles. Analyze your object graph and prevent strong cycles with weak
and unowned
references. Alternatively, use value types (struct
, enum
) to prevent cycles altogether.
代码(即使是非生产环境、教程演示的代码)都不应该出现循环引用。分析你的对象关系图并用 weak
和 unowned
来防止循环引用。或者使用值类型(struct
、enum
)来杜绝循环引用。
延长对象的生命周期/Extending object lifetime
Extend object lifetime using the [weak self]
and guard let self = self else { return }
idiom. [weak self]
is preferred to [unowned self]
where it is not immediately obvious that self
outlives the closure. Explicitly extending lifetime is preferred to optional chaining.
使用惯用语法 [weak self]
和 guard let self = self else { return }
来延长对象的生命周期。 在 self
超出闭包生命周期不明确的情况下,优先使用 [weak self]
而不是 [unowned self]
。利用固定代码明确延长对象的生命周期优于可选链的书写方式。
推荐(Preferred):
resource.request().onComplete { [weak self] response in
guard let self = self else {
return
}
let model = self.updateModel(response)
self.updateUI(model)
}
不推荐(Not Preferred):
// might crash if self is released before response returns
resource.request().onComplete { [unowned self] response in
let model = self.updateModel(response)
self.updateUI(model)
}
不推荐(Not Preferred):
// deallocate could happen between updating the model and updating UI
resource.request().onComplete { [weak self] response in
let model = self?.updateModel(response)
self?.updateUI(model)
}