Junior — Middle
Milline on erinevus Weak ja Unowned viidete vahel mälu haldamisel?
sobes.tech AI
Vastus AI-lt
In Swift, weak and unowned references are used to prevent strong reference cycles (retain cycles) in memory management, but they differ in behavior and application.
-
Weak:
- Can be
nil. - Declared as an optional type (
var delegate: SomeDelegate? weak). - Used when the reference can become
nilduring the object's lifetime, e.g., delegates. - The system automatically sets the
weakreference tonilwhen the referenced object is deallocated.
- Can be
-
Unowned:
- Cannot be
nil(non-optional type). - Used when the reference is guaranteed to exist during the object's lifetime, e.g., between a parent and a child.
- If the referenced object has already been deallocated, accessing it will cause a runtime error (crash).
- Cannot be
Example:
class Person {
var apartment: Apartment?
}
class Apartment {
unowned let tenant: Person
init(tenant: Person) {
self.tenant = tenant
}
}
// Here, tenant is unowned because an apartment cannot exist without a tenant.
class DelegateHolder {
weak var delegate: SomeDelegate?
}
// The delegate is weak because it can be deallocated earlier.
Thus, weak is suitable for references that can become nil, and unowned for references that should always be valid during the object's lifetime.