When to use strong , weak and unowned references?
When to use strong , weak and unowned references?
In Swift, understanding when to use strong, weak, and unowned references is crucial for effective memory management and avoiding retain cycles. Here’s a detailed explanation of each type of reference and when to use them:
A strong reference is the default type of reference in Swift. When you create a strong reference to an object, it increments the reference count of that object by one. As long as there is at least one strong reference to an object, it will not be deallocated.
class HomeVC: UIViewController {
let api = API() // Strong reference
}
A weak reference does not increment the reference count of the object it points to. This means that the object can be deallocated even if there are weak references to it. Weak references are always optional and automatically set to nil
when the object they reference is deallocated.
class Child {
weak var parent: Parent? // Weak reference to avoid retain cycle
}
protocol MyDelegate: AnyObject {
func didSomething()
}
class MyClass {
weak var delegate: MyDelegate? // Weak reference to delegate
}
self
in a closure, use [weak self]
to avoid retain cycles.api.completion = { [weak self] data, error in
self?.handleResponse(data, error)
}
An unowned reference is similar to a weak reference in that it does not increment the reference count. However, unlike weak references, unowned references are non-optional and assume that the referenced object will always exist as long as the unowned reference exists. If the referenced object is deallocated and the unowned reference is accessed, it will cause a runtime crash.
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào