Memory Management

ARC

The automatic memory management method used by Apple is called ARC (Automatic Reference Counting).

As its own name says, the reference count is used to determinate whether a memory block should or should not be deallocated.

When an object is created, its reference count begins with 1. This reference count can increase or decrease during its lifecycle. At last, when the reference count reaches 0, the object is deallocated from memory.

Strong, Weak, Unowned References

  • Variables are strong by default.
  • Strong variables increase the reference count
  • Weak and unowned variables do not increase the reference count
  • Weak reference will be automatically set to nil

  • Weak reference is used where there is possibility for that reference to become nil at some point during its lifetime.

  • Unowned reference is used when the other instance has the same lifetime or a longer lifetime.

Memory Leak

A memory leak occurs when a content remains in memory even after its lifecycle has ended.

Case 1: Protocols

When we declare a protocol we can specify that only class types can adopt it.

protocol ListViewControllerDelegate : class {
    func configure(with list : [Any])
}

class ListViewController : UIViewController {

    weak var delegate : ListViewControllerDelegate?

    override func viewDidLoad() {
        super.viewDidLoad()
    }

}

Case 2: Closures

Closures can cause retain cycles for a single reason: by default, they have a strong reference to the object that uses them.

class Example {
    private var counter = 0

    private var closure : (() -> ()) = { }

    init() {
        closure = {
            self.counter += 1
            print(self.counter)
        }
    }

    func foo() {
        closure()
    }

}

results matching ""

    No results matching ""