iPhone: Good idea to dealloc and rellocate UI items when switching views? - iphone

Suppose I have 2 views. In the first view, I allocate memory to displaying many UI components such as an UILabel, UIImages, etc.
Suppose the user navigates to the next view (via UINavigationController)
Is it OK to deallocate memory assigned to displaying UI components in the first view and then initialize them again once the user goes back to the first view (in viewFirstLoad or the appropriate function)?
It seems to me if you don't do this, then memory will keep on increasing the longer the user uses your app in that particular session.
Is this not allowed? frowned upon? impossible?

It is perfectly normal and in fact, that functionality is built in standard UIViewController - when controller is not displayed its view may be released from memory and you can release all its subviews (e.g. retained through IBOutlet references) in controller's -viewDidUnload method.
When controller needs to display again it reloads its view again.

It depends. Generally, the rule of thumb is that you should free objects that you don't need. If your view is just a view, then yes, I'd release it and all of its subviews. If your view has data that was obtained through a lengthy retrieval process (e.g. a web service call), I'd probably hold onto the data somewhere so that I don't have to go back out and retrieve it when the user goes back to the first view.

To clarify a little: Apple recommends you display data specific to a view in it's -viewDidLoad method, such as setting text on labels. Then, in -viewDidUnload you should release (or nil outlets of) the view objects you setup in -viewDidLoad. It's critical you implement -viewDidLoad, as the base UIViewController code checks that it's subclass actually implements -viewDidLoad before it assumes it can unload the view (and therefore call -viewDidUnload). Failing to implement -viewDidLoad results in the controller thinking it can't recreate your view at a later time, and so it doesn't unload the view from memory. A developer I know experienced this same problem, took forever to track down.

Related

Storyboard Controllers not Deallocating

My Initial View Controller of the storyboard load another view controller using performSegue:withIdentifier method which in turn loads some other controller using same performSegue:withIdentifier method.
However, neither the initial view controller nor the second view controller are deallocating. They both tend to have a reference count of 1 as seen via instruments.
I need to send user back to first controller when he logs out of application. The only way I have figured so far is to use performSegue:withIdentifier method and send the user back to initial controller.
However, it concerns me that previous controllers will not have been deallocated thus, resulting in re-creation same view controllers.
Since I need to logout a user back to first screen, I want to make sure that all previous view controllers have been deallocated.
When you perform a push or modal segue, it will not (and should not) release the view controller from which you're seguing. It needs to keep it so that when you pop/dismiss back to it, it will still be there. The exception to this rule is when using a split view controller and you use a replace segue. But that's a special case.
If you want to go back to the first scene, if you're using a navigation controller and using only push segues, you can use popToRootViewControllerAnimated. (For iOS 5 targets, I'll always use navigation controller, and hide the navigation bar if I don't want it visible, for that reason. It's convenient to be able to pop back multiple levels. It's cumbersome to achieve the same effect with modal segues.) In iOS 6, you can use an unwind segue, in which you can pop/dismiss back an arbitrary number level of scenes, for example, to return to your initial scene.
Looping with performSegue is not a good idea..
If you have to go back in your VC hierarchy, you should either use a UINavigationController with pushing/poping VCs, or presenting/dismissing a modal VC. You can combine both by modally presenting a UINavigationController.
Prior to iOS 6 A UIViewController will stay alive but its more expensive UIView will be deallocated to save memory. The UIViewController itself is pretty light compared to a UIView.
Since iOS 6 you should according to the documentation override didReceiveMemoryWarning
Docs for UIViewController:
Memory Management
Memory is a critical resource in iOS, and view controllers provide
built-in support for reducing their memory footprint at critical
times. The UIViewController class provides some automatic handling of
low-memory conditions through its didReceiveMemoryWarning method,
which releases unneeded memory.
Prior to iOS 6, when a low-memory warning occurred, the
UIViewController class purged its views if it knew it could reload or
recreate them again later. If this happens, it also calls the
viewWillUnload and viewDidUnload methods to give your code a chance to
relinquish ownership of any objects that are associated with your view
hierarchy, including objects loaded from the nib file, objects created
in your viewDidLoad method, and objects created lazily at runtime and
added to the view hierarchy. On iOS 6, views are never purged and
these methods are never called. If your view controller needs to
perform specific tasks when memory is low, it should override the
didReceiveMemoryWarning method.
As long as you manage you correctly react (depends on the iOS Version) and dealloc the view I see no problems here.

Initializing a View Controller

When a view controller is first instantiated, it usually creates or
loads objects it needs through its lifetime. It should not create
views or objects associated with displaying content. It should focus
on data objects and objects needed to implement other critical
behaviors.
The above is from the iOS reference :
http://developer.apple.com/library/ios/#featuredarticles/ViewControllerPGforiPhoneOS/ViewLoadingandUnloading/ViewLoadingandUnloading.html#//apple_ref/doc/uid/TP40007457-CH10
The documentation goes on to describe a view load sequence with Storyboard.
My question are :
1
Since a view controller would be associated with a nib file, which contains view objects; And its "viewDidLoad" method seems to be designed for configuring view objects at load time. So how should the documentation's suggestion :
"should not create views or objects associated with displaying content"
be interpreted ?
2
Does question 1 related to whether we use Storyboard or not ?
Not sure I get your question right, but here's my explanation:
initialization and view creation are two separate steps. Let's say I have a view controller with table as IBOutlet which should display a list of recipes stored in core data. In my initialization method I'd fetch the data from CoreData and store it in an array or fetched results controller. I don't need table for that, hence I do nothing with self.view property (which calls the viewDidLoad if there is no view yet). In viewDidLoad I call [tableView reloadData] to redraw the cells so that they display the data from my controller created in controller's initializer.
I don't think it's related, but storyboard should be mere scaffold for your view controllers replacing separate nibs with single file.
The statement you quoted has a lot to do with mobile device limitation and design efficiency. It does not relate to Storyboard in particular.
By "instantiating", the documentation meant the -(id)init; call. When this happens, the controller "prepares critical data, but not creates views". This means the controller evaluates a xib file, and constructs an internal hierarchical representation of the views upon init. This step involves only RAM and CPU.
View controller only creates views when it's pushed into the navigation controller, or view transition animation (that's when viewDidLoad kicks in). This is because views are expensive. It involves GPU and Video RAM. Video RAM is much more limited than RAM, it's not efficient to just create views (back buffer in VRAM) when it's not necessary to display.
If you look at your project, you should discover some view controllers being initialized but are not immediately required to show. Without such design, VRAM will drain quickly for no reason.

Reloading subviews of UINavigationController

I'm kind of new to iPhone development so bear with me.
I have an application wherein I display a lot of data in a tableviews, edit it in a detailview etc. However, I also have a login-system.
The problem I have is that I can't figure out how to reload the subviews of the NavigationController when I've logged out, or how to dealloc it completely and reinitialize it upon a succesful login.
This means that data from the last user who logged out is still present in my tableview when I log in as another user, as the data is set to reload only when the view loads for the first time.
Thankful for any and all contributions.
There are probably several ways you could go about this; it's up to you (and without more information about your app, I can't suggest a particular solution). You might consider:
-viewWillAppear: — this method is called on any UIViewController subclass when it's about to (re)appear as part of a UINavigationController stack (or tab bar controller, etc.). You can clear out fields, etc. This is mostly useful when a view controller reappears (being uncovered or switched to), because you usually create a new view controller instance each time you display one.
Notifications and delegates — your view controllers (and other objects) can communicate with each other about when a logout occurs, and reconfigure themselves as necessary.

IPhone - Which View Controller methods to use

I'm trying to figure out what logic should go into the different UIViewController methods like viewDidLoad, viewDidAppear, viewWillAppear, ...
The structure of my app is that I have a root view controller that doesn't really have a view of its own, rather it has a tab view controller and loads other view controllers into it. But in the future, it may have to load other view controllers instead of the tab bar controller depending on app logic.
My main question is, what do people usually put into the viewDidLoad, .... methods.
Currently I:
viewDidLoad - setup the tab bar controller and set its view to the view controller's own view
viewDidAppear - check if user has stored login info
if not - present with login
if so, login and get app data for first tab
I'm trying to figure out now if my logic for setting up my tab bar controller should go into loadView rather than viewDidLoad.
Any help would be great. Small examples found on the web are great, but they don't go into detail on how larger apps should be structured.
You should not implement both -viewDidLoad and -loadView; they are for different purposes. If you load a NIB, you should implement -viewDidLoad to perform any functions that need to be done after loading the NIB. Wiring up the tabbar is appropriate there if you haven't already done it in the NIB.
-loadView should be implemented if you do not use a NIB, and should construct the view.
-viewWillAppear is called immediately before you come onscreen. This is a good place to set up notification observations, update your data based on model classes that have changed since you were last on screen, and otherwise get your act together before the user sees you. You should not perform any animations here. You're not on the screen; you can't animate. I see a lot of animation glitches due to this mistake. It kind of works, but it looks weird.
-viewDidAppear is called after you come onscreen. This is where you do any entry animations (sliding up a modal, for instance; not that you should do that very often, but I was just looking at some code that did).
-viewWillDisappear is called right before you go offscreen. This is where you can do any leaving animations (including unselecting tableview cells and the like).
-viewDidDisappar is called after you're offscreen (and the animations have finished). Tear down any observations here, free up memory if possible, go to sleep as best you can.
I touch on setting up and tearing down observations here. I go into that in more depth in View controllers and notifications.
viewDidLoad will be called once per lifetime of each UIViewController's view. You put stuff in there that needs to be set up and working before the user starts interacting with the view.
viewDidAppear is called whenever the view has appeared to the user. It could potentially be called more than once. An example would be the root screen of an app using a UINavigationController to push and pop a hierarchy of views. Put stuff in there that you'd want done every time. For example, you might want to hide the UINavigationBar of the root screen, but show it for all subscreens, so you'd do the hiding of the bar here.
Therefore, you'd put your logic for setting up your UITabBarController in viewDidLoad, since it only should be done once.
Regarding your app, is there a reason why you don't just make the UITabViewController be the controller loaded by your app delegate? It seems that you have a level of indirection in your app that you may or may not need. It's probably better to simplify it now, and refactor later if you need something more complex.

set view property in a UIViewController from a NIB programmatically (not during initialization)

At the beginning of my app, I am initializing a UIViewController with a NIB.
At some point, I am removing the view from the screen, then releasing it, so it no longer takes up memory. (At this point I am also saving the state of the view in the UIViewController)
At a later point, I want to recreate the view and bring it back on screen. I will then restore its state. (Using the same UIViewController, not a new one, since it saved the state)
My question, is when I recreate the view, how do I do so from the NIB, or is this not possible?
To me, the obvious remedies are:
Don't save state in the UIViewcontroller (Where does convention dictate that I do save state?)
Don't release the view (maybe just release all of its subviews?)
Don't load my view from a NIB, create programmatically (seems to go against using IB for everything)
Note:
I am not using a UINavigationController, I am handling the swapping of the views myself, since thee are only 2 of them.
If you need that level of control, you dont really want to use IB. Because, as you noted, if remove the view and then later recreate it, you would have to do it in code then anyway. Just design most of the views in IB, then write some code that generates just this view. Then you can call that same method again later to recreate that view when you need it.
You may be able to archive it and later turn it back into an object, but that seems like an inelgant solution. IB does not allow for dynamic creation of controls at runtime, even if they used to exist but don't anymore. There is no shame in leaving IB out of loop for this. In fact it's probably a good idea.
OR
If its a complicated view with a lot of pieces, put the view in it's own nib, and make a view controller for it. Then you can simply instatiate the view controller with the nib name, and add the controllers view as a subview to you main view. Then your view controller handles loading of the nib, and you get to design it in IB. Nothing says the view of a view controller has to take up the entire screen either.
self.otherController = [[OtherController alloc] initWithNibName:#"Other" bundle:nil];
[self.view addSubview:otherController.view];
Don't create the view controller and the view in the same nib file; either create the controller in code or put the view in a separate nib file. If you later nil out your controller's view property, the controller should recreate the view.
But why are you so worried about this? There's already a mechanism to automatically free up the view if you're low on memory: the low memory warning. It will only destroy and recreate the view if you actually need to do so, and it's built in to the system so you don't have to do anything. Remember the saying about premature optimization?