Junior — Middle
Kus tavaliselt rakendatakse mälu haldamise jaoks viidete loendurit?
sobes.tech AI
Vastus AI-lt
Reference counter for memory management is usually implemented at the object level or its wrapper (runtime), where each object stores the number of active references to it. When a new reference is created, the counter increases; when a reference is removed, it decreases. If the counter reaches zero, the object is released.
On iOS with ARC (Automatic Reference Counting), this is implemented by the compiler and the Objective-C/Swift runtime. Developers typically do not write manual code for the counter but must monitor strong and weak references to avoid cyclic dependencies.
Example in Swift:
class Person {
var name: String
init(name: String) { self.name = name }
}
var p1: Person? = Person(name: "Alice") // counter = 1
var p2 = p1 // counter = 2
p1 = nil // counter = 1
p2 = nil // counter = 0, object is released
Thus, the reference counter is generally implemented in runtime and managed automatically.