Explain the difference between weak and...
Explain the difference between weak and...
In Swift, both weak and unowned references are used to avoid strong reference cycles, which can lead to memory leaks. However, they have distinct characteristics and use cases.
A weak reference is a reference that does not prevent the referenced object from being deallocated. When the object is deallocated, the weak reference is automatically set to nil
. This means that weak references must always be optional types.
Characteristics:
nil
when the referenced object is deallocated.nil
.Example:
class Parent {
var child: Child?
}
class Child {
weak var parent: Parent?
}
var parent: Parent? = Parent()
var child: Child? = Child()
parent?.child = child
child?.parent = parent
parent = nil
// At this point, the child’s parent reference is automatically set to nil
An unowned reference is a non-optional reference that does not keep a strong hold on the referenced object. Unlike weak references, unowned references are not set to nil
when the referenced object is deallocated. Instead, accessing an unowned reference after the object has been deallocated will cause a runtime crash.
Characteristics:
nil
when the referenced object is deallocated. Accessing a deallocated unowned reference will cause a runtime error.Example:
class Customer {
var card: CreditCard?
}
class CreditCard {
unowned let customer: Customer
init(customer: Customer) {
self.customer = customer
}
}
var customer: Customer? = Customer()
customer?.card = CreditCard(customer: customer!)
// At this point, the customer and card reference each other
customer = ni...
senior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào