Memory Management

suggest change

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 structure.

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()
    }
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents