James Franco
James Franco

Reputation: 4706

Does dismissing a view controller call destructor of the ViewController

I have two view controllers ViewControllerA and ViewControllerB.

Now ViewControllerA launches ViewControllerB through an action as such

 self.view_library = [[ViewControllerB alloc] initWithNibName:@"ViewControllerB" bundle:nil]; //Initialize a view controller/
[self presentViewController:self.view_library animated:YES completion:nil]; //Display the new view controller

Now in ViewControllerB i return the control back to ViewControllerA as such

 [self dismissViewControllerAnimated:YES completion:Nil];

My question is will the destructor of ViewControllerB be called ? Will I have to alloc it again to display it ?

Upvotes: 0

Views: 260

Answers (2)

Rob Napier
Rob Napier

Reputation: 299275

You're likely not thinking about this correctly. This line creates a strong reference to a new ViewControllerB instance:

self.view_library = [[ViewControllerB alloc] initWithNibName:@"ViewControllerB" bundle:nil]; //Initialize a view controller/

(Don't put underscores in your variable names; this is confusing to ObjC and bad for key-value-coding conventions that Cocoa relies on.)

This line probably (but it isn't your business) adds an extra retain to the view controller:

[self presentViewController:self.view_library animated:YES completion:nil]; //Display the new view controller

This line probably (but it isn't your business) removes a retain from the view controller:

[self dismissViewControllerAnimated:YES completion:Nil];

So, adding together what is certain with what is likely, that's +1, +1, -1. So you still have one retain on the object, and it will not be deallocated (dealloc is not the same as a destructor; that's related to C++ and has different semantics).

If, after dismissing the view controller, you set self.view_library to something else, then its retain will be removed from the object, and (if nothing else has retained it) the view controller will be deallocated.

The point is that you need to focus on balancing your retains and releases, which is mostly handled for you by ARC (one is retained when you assign to a strong variable, and one is released when that strong variable stops referring to it).

To your specific question, yes, should likely re-create the view controller. That's the common solution, even if it's not always required.

Upvotes: 3

DrKey
DrKey

Reputation: 3495

If you are using ARC and self.view_library has strong reference it will not be deallocated, so you don't need to alloc it again.

Upvotes: 0

Related Questions