Junior — Middle
Kuidas õigesti korraldada lingid objekti mudelis, et vältida mälu tsüklit?
sobes.tech AI
Vastus AI-lt
To prevent memory retention cycles in the object model on iOS (using Swift or Objective-C), it is important to correctly use strong, weak, and unowned references.
Main idea:
- strong — owning reference, increases the reference count of the object.
- weak — non-owning reference, does not increase the count, automatically set to nil when the object is deallocated.
- unowned — non-owning reference, does not increase the count, not set to nil, used when the object is guaranteed to live longer.
Cycles often occur, for example, between parent and child or between delegate and object. To avoid cycles:
- The parent holds the child via strong.
- The child references the parent via weak or unowned.
Example in Swift:
class Parent {
var child: Child?
}
class Child {
weak var parent: Parent? // weak reference to avoid cycle
}
let parent = Parent()
let child = Child()
parent.child = child
child.parent = parent
This way, when parent and child are no longer used, memory is released correctly, avoiding cycles and leaks.