简体   繁体   中英

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM