Sobes.tech
Junior — Middle

Can you explain what is meant by 'Unowned' in memory management?

sobes.tech AI

Answer from AI

In the context of memory management in iOS (and Swift), the term "Unowned" refers to a weak reference to an object that does not increase the reference count (retain count), but assumes that the object exists during the use of this reference.

Differences from weak:

  • A weak reference can become nil if the object is deallocated, and is therefore declared as optional.
  • An unowned reference is not optional and does not automatically become nil. If the object referenced by unowned is deallocated, attempting to access it will lead to a runtime error (crash).

It is used when it is guaranteed that the lifetime of the object being referenced is longer than or equal to the lifetime of the reference.

Example:

class Owner {
    var pet: Pet?
}

class Pet {
    unowned let owner: Owner
    init(owner: Owner) {
        self.owner = owner
    }
}

let owner = Owner()
owner.pet = Pet(owner: owner)

Here, Pet holds an unowned reference to Owner, assuming that Owner lives longer than Pet.