mahieddine
mahieddine

Reputation: 565

What it is the best way to release UIViewController in iOS

I'm currently building a little sample iOS app, i developed my UIViewControllers and views programatically, i'm targeting iOS 7+ devices and i have a simple question : Here how i show a new controller

 MySuperController *superController = [[MySuperController alloc] init];
[self.navigationController showViewController:superController sender:self.navigationController];

First i wanted to know if it's the correct way to show another view controller ? Second imagine i'm performing those instructions in a LoginViewController that will be displayed just once (typically when the user launches the app) how can i release this loginviewcontroller after creating and showing another view controller ? i know this question has been already asked but all the solutions presented are old/inappropriate (my sample app is ARC enabled which is by default enabled i think)

I'm new to this environnement any help/indication is appreciated thank you

Upvotes: 1

Views: 1206

Answers (2)

Duncan C
Duncan C

Reputation: 131426

As Roy Nakum says in his comment, if you are using ARC, your code is fine. You create your view controller using a local strong variable, then present it. At that point the navigation controller takes ownership of it. Since your strong reference is a local variable, it does not keep ownership after your method returns.

However there is another problem with your code. This line will likely cause you problems:

MySuperController *superController = [[MySuperController alloc] init];

You should not use init to create a view controller. It won't have any contents. You should either use initWithNibName:bundle: (to load a view controller from a NIB) or instantiateViewControllerWithIdentifier (to load a view controller from a storyboard.)

It is possible to set up a view controller so its "plain" init method loads it's views, but it takes special handling in the init method, and it's not the normal way to do things.

Upvotes: 1

Dante Puglisi
Dante Puglisi

Reputation: 668

That's a good way to present a ViewController. If you have ARC enable (default) don't worry about releasing, it will release automatically.

Upvotes: 1

Related Questions