Memory Management

suggest change

Introduction

This topic outlines when the Swift runtime allocates memory for application data structures, and when that memory is reclaimed.

By default, the memory for class instances is managed through reference counting. Struct values are passed by copying. To opt out of the built-in memory management scheme, use the Unmanaged structure.

Remarks

When to use the weak-keyword:

Use weak if the referenced object may be deallocated during the lifetime of the object holding the reference.

When to use the unowned-keyword:

Use unowned if the referenced object is not expected to be deallocated during the lifetime of the object holding the reference. A dangling unowned reference traps when it is used.

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: NSObject, CLLocationManagerDelegate {
    override init() {
        super.init()
        let locationManager = CLLocationManager()
        locationManager.delegate = self
        locationManager.startUpdatingLocation()
    }
}

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: NSObject, CLLocationManagerDelegate {
    let locationManager: CLLocationManager

    override init() {
        locationManager = CLLocationManager()
        super.init()
        locationManager.delegate = self
        locationManager.startUpdatingLocation()
    }
}

Feedback about page:

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



Table Of Contents