Trong iOS, bạn xử lý bộ nhớ như thế nào để tránh retain cycle khi dùng closures?
Trong iOS, bạn xử lý bộ nhớ như thế nào để tránh retain cycle khi dùng closures?
Retain cycle với closure xảy ra khi object giữ closure mạnh và closure bắt self mạnh.
class ViewModel {
var onUpdate: (() -> Void)?
func bind() {
onUpdate = { self.render() } // self → onUpdate → self: cycle
}
}
onUpdate = { [weak self] in
guard let self else { return } // Swift 5.7+
self.render()
}
onUpdate = { [unowned self] in self.render() } // chỉ khi self chắc chắn sống lâu hơn closure
weak: self có thể đã huỷ; self thành nil an toàn. Mặc định an toàn.Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.