Automatic reference counting used to manage memory in Swift programming

  • 2020-05-14 05:00:44
  • OfStack

The Swift memory management feature is handled by using automatic reference counting (ARC). ARC is used to initialize and uninitialize the system resource, thereby freeing the memory space of the class instance used when the instance is no longer needed. Instances of ARC trace code effectively manage information about relationships between stored resources.

The function of ARC

ARC allocates 1 block of memory to store information every time a new class instance is created. init() Information about instance types and their values is stored in storage When the class instance no longer needs it automatically freed by deinit(), the storage space used for the storage and retrieval of the step 1 class instance ARC is kept on the track for the current reference class instance's properties, constants, and variables, making deinit() applicable only to instances that are not in use. ARC maintains "strong references" to these class instance properties, constants, and variables to limit the release when the current class instance is in use.

ARC program


class StudDetails {
    var stname: String!
    var mark: Int!
    init(stname: String, mark: Int) {
        self.stname = stname
        self.mark = mark
    }
   
    deinit {
        println("Deinitialized \(self.stname)")
        println("Deinitialized \(self.mark)")
    }
} let stname = "swift"
let mark = 98 println(stname)
println(mark)

When we run the above program using playground, we get the following results.


swift
98

ARC strong reference periodic class instances


class studmarks {
    let name: String
    var stud: student?
   
    init (name: String) {
        println("Initializing: \(name)")
        self.name = name
    }
   
    deinit {
        println("Deallocating: \(self.name)")
    }
} class student {
    let name: String
    var strname: studmarks?
   
    init (name: String) {
        println("Initializing: \(name)")
        self.name = name
    }
   
    deinit {
        println("Deallocating: \(self.name)")
    }
} var shiba: studmarks?
var mari: student? shiba = studmarks(name: "Swift")
mari = student(name: "ARC") shiba!.stud = mari
mari!.strname = shiba

When we run the above program using playground, we get the following results.


Initializing: Swift
Initializing: ARC

ARC weak and no master reference
There are two ways to deal with strong reference cycles for Class type properties:

A weak reference No main reference

These references are used to make 1 instance refer to other instances in 1 benchmark cycle. The instance can then handle the strong reference cycle for each instance reference instead. When the user knows that the 'nil' value may be returned in some cases, we may point to the use of weak references. When the instance returns something that is not zero, then use the no master reference declaration.

Weak reference program


class module {
    let name: String
    init(name: String) { self.name = name }
    var sub: submodule?
    deinit { println("\(name) Is The Main Module") }
} class submodule {
    let number: Int
   
    init(number: Int) { self.number = number }
   
    weak var topic: module?
   
    deinit { println("Sub Module with its topic number is \(number)") }
} var toc: module?
var list: submodule?
toc = module(name: "ARC")
list = submodule(number: 4)
toc!.sub = list
list!.topic = toc toc = nil
list = nil

When we run the above program using playground, we get the following results.


ARC Is The Main Module
Sub Module with its topic number is 4

No master reference program


class student {
    let name: String
    var section: marks?
   
    init(name: String) {
        self.name = name
    }
   
    deinit { println("\(name)") }
}
class marks {
    let marks: Int
    unowned let stname: student
   
    init(marks: Int, stname: student) {
        self.marks = marks
        self.stname = stname
    }
   
    deinit { println("Marks Obtained by the student is \(marks)") }
} var module: student?
module = student(name: "ARC")
module!.section = marks(marks: 98, stname: module!)
module = nil

When we run the above program using playground, we get the following results.


ARC
Marks Obtained by the student is 98

Closure strong reference cycles
When we assign a closure to a class instance property, the body of the closure captures the occurrence of a strong reference period for a particular instance. Strong reference closure is defined by self.someProperty or self.someMethod (). Strong reference cycles are used as closure reference types.


class HTMLElement {
    let samplename: String
    let text: String?
   
    lazy var asHTML: () -> String = {
        if let text = self.text {
            return "<\(self.samplename)>\(text)</\(self.samplename)>"
        } else {
            return "<\(self.samplename) />"
        }
    }
   
    init(samplename: String, text: String? = nil) {
        self.samplename = samplename
        self.text = text
    }
   
    deinit {
        println("\(samplename) is being deinitialized")
    }
} var paragraph: HTMLElement? = HTMLElement(samplename: "p", text: "Welcome to Closure SRC")
println(paragraph!.asHTML())

When we run the above program using playground, we get the following results.

< p > Welcome to Closure SRC < /p >
Weak and no master reference
When a closure and an instance refer to each other, the user can define a closure to be captured as an ownerless reference. It does not allow users to unallocate instances at the same time. When the instance at some point returns a "nil" definition and USES the value of the weak instance.


 class HTMLElement {
    let module: String
    let text: String?
   
    lazy var asHTML: () -> String = {
        [unowned self] in
        if let text = self.text {
            return "<\(self.module)>\(text)</\(self.module)>"
        } else {
            return "<\(self.module) />"
        }
    }
   
    init(module: String, text: String? = nil) {
        self.module = module
        self.text = text
    }
   
    deinit {
        println("\(module) the deinit()")
    }
} var paragraph: HTMLElement? = HTMLElement(module: "Inside", text: "ARC Weak References")
println(paragraph!.asHTML())
paragraph = nil

When we run the above program using playground, we get the following results.


<Inside>ARC Weak References</Inside>
Inside the deinit()


Related articles: