hasan83 hasan83 -4 years ago 103
Swift Question

Prevent deallocating an object defined in function

A function on a UIViewController declares and initializes a reference to a class object. That class has a weak delegate ref. which has been set to the UIViewController. After this function finishes execution the object gets deallocated and its no longer calling the delegate methods.

func registerDevice() {

let notificationModel: NotificationModel = NotificationModel(delegate: self)


Is there a way to keep this object alive until the UIViewController dies, without having a global class ref. on the UIViewController to it. This is important because there isn't any use for this object in any other function or in any other situations.

Answer Source

Since you are declaring notificationModel as a constant within the scope of the registerDevice function, the lifetime of that object is limited to that function in the absence of any other strong reference being held.

You say "there isn't any use for this object in any other function or in any other situations.", but this isn't correct; Since your view controller implements delegate functions for this object and you expect those delegate functions to be called, your view controller needs to take responsibility for keeping the model object in memory.

It can do this by simply declaring an instance property

var notificationModel: NotificationModel?

and assigning the object to that property in your function:

func registerDevice() {

    self.notificationModel = NotificationModel(delegate: self)


Now the lifetime of your model object is (at least) the lifetime of your view controller.

Note, that this property is not a class property or a global; it is scoped to the specific View Controller instance.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download