Sobes.tech
Junior

Kas ir strong atmiņas modifikatori?

sobes.tech AI

Atbilde no AI

Swift strong modifikators norāda, ka atsauce uz objektu palielina šī objekta atsauces skaitītāju par vienu. Tas nozīmē, ka objekts paliks atmiņā tik ilgi, kamēr pastāv vismaz viena stipra atsauce uz to.

Pēc noklusējuma tas tiek izmantots atsauces tipiem (klasēm). Piešķirot nil mainīgajam ar strong modifikatoru, samazina atsauces skaitītāju. Kad skaitītājs sasniedz nulli, objekts tiek atbrīvots no atmiņas.

Piemērs:

class Person {
    var name: String
    init(name: String) {
        self.name = name
        print("\(name) tiek inicializēts")
    }
    deinit {
        print("\(name) tiek de-inicializēts")
    }
}

var reference1: Person?
var reference2: Person?

reference1 = Person(name: "Alice") // Alice atsauces skaitītājs: 1
reference2 = reference1           // Alice atsauces skaitītājs: 2

reference1 = nil                   // Alice atsauces skaitītājs: 1
reference2 = nil                   // Alice atsauces skaitītājs: 0, Alice tiek de-inicializēta