Stats

419 Contributors: 7
2016-12-11
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial: info@zzzprojects.com

Download eBook

Memory Management

Download swift eBook

Introduction

This topic outlines how and when the Swift runtime shall allocate memory for application data structures, and when that memory shall be reclaimed. By default, the memory backing class instances is managed through reference counting. The structures are always passed through copying. To opt out of the built-in memory management scheme, one could use [Unmanaged][1] structure. [1]: https://developer.apple.com/reference/swift/unmanaged

Remarks

When to use the weak-keyword:

The weak-keyword should be used, if a referenced object may be deallocated during the lifetime of the object holding the reference.

When to use the unowned-keyword:

The unowned-keyword should be used, if a referenced object is not expected to be deallocated during the lifetime of the object holding the reference.

Pitfalls

A frequent error is to forget to create references to objects, which are required to live on after a function ends, like location managers, motion managers, etc.

Example:

class A : CLLocationManagerDelegate
{
    init()
    {
        let locationManager = CLLocationManager()
        locationManager.delegate = self
        locationManager.startLocationUpdates()
    }
}

This example will not work properly, as the location manager is deallocated after the initializer returns. The proper solution is to create a strong reference as an instance variable:

class A : CLLocationManagerDelegate
{
    let locationManager:CLLocationManager

    init()
    {
        locationManager = CLLocationManager()
        locationManager.delegate = self
        locationManager.startLocationUpdates()
    }
}

Related Examples