Sobes.tech
Middle

Millised lingid on sitetable objekti sees?

sobes.tech AI

Vastus AI-lt

Strong, weak, and unowned references.

  • Strong: Creates an ownership of the object, preventing its deallocation as long as strong references exist.
  • Weak: Does not create an ownership. If the object it references is deallocated, the weak reference automatically becomes nil. Used to prevent strong reference cycles, often for references to parent objects or delegates.
  • Unowned: Does not create an ownership. Similar to weak, but guarantees that the referenced object will exist for the lifetime of the unowned reference. Accessing the object after its deallocation will cause a runtime error (crash). Used when objects have the same or related lifecycle, and nil is permissible but not expected.
// Example of Strong
class Parent {
    var child: Child?
}

class Child {
    var parent: Parent?
}

var parent: Parent? = Parent()
var child: Child? = Child()

parent?.child = child
child?.parent = parent // Creates a strong reference cycle

parent = nil // Parent will not be deallocated due to strong reference from child
child = nil // Child will not be deallocated due to strong reference from parent

// Example of Weak
class ParentWeak {
    var child: ChildWeak?
}

class ChildWeak {
    weak var parent: ParentWeak? // Weak reference

    deinit {
        print("ChildWeak deallocated")
    }
}

var parentWeak: ParentWeak? = ParentWeak()
var childWeak: ChildWeak? = ChildWeak()

parentWeak?.child = childWeak
childWeak?.parent = parentWeak

parentWeak = nil // ParentWeak deallocated
// ChildWeak deallocated

// Example of Unowned
class ParentUnowned {
    var child: ChildUnowned?
}

class ChildUnowned {
    unowned var parent: ParentUnowned // Unowned reference

    init(parent: ParentUnowned) {
        self.parent = parent
    }

    deinit {
        print("ChildUnowned deallocated")
    }
}

var parentUnowned: ParentUnowned? = ParentUnowned()
var childUnowned: ChildUnowned? = ChildUnowned(parent: parentUnowned!) // ParentUnowned must exist

parentUnowned?.child = childUnowned

parentUnowned = nil // ParentUnowned deallocated, ChildUnowned deallocated