4

I'm creating a UIViewController subclass, and I create it with a custom init function, initWithImages:(NSArray *)images, that then returns the view controller for use.

I'm confused however what I'm supposed to do in the init versus the viewDidLoad, viewWillAppear, etc. functions. In this init function I set up the image view, a caption label and give it gesture recognizers, but are those things that should only be done when it loads or appears?

Should the init be as small as possible? What do I put in each is basically my question?

I'm using the UIViewControllers with a UIPageViewController so it's important that even with a bunch of view controllers in the page view controller that memory isn't used absurdly, so I want to make sure I'm doing this right.

jscs
  • 63,694
  • 13
  • 151
  • 195
Doug Smith
  • 29,668
  • 57
  • 204
  • 388
  • 2
    Please, take some time and accept answers to your earlier questions. It's not nice to keep asking so many questions without rewarding people that take the time to help you. – rmaddy Feb 16 '14 at 21:53

3 Answers3

4

init should be used for data related basic initialisation. viewDidLoad Should be used for view based initialisation, because the view has been created at that point in time so you can add subviews. There is no point creating subviews if you can't use them yet.

Wain
  • 118,658
  • 15
  • 128
  • 151
3

The main difference is that self.view is not created in init method. So everything like

[self.view addSubview:some_subview]

should be placed in viewDidLoad

UIViewController methods are called in the following order:

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
- (void)loadView;
- (void)viewDidLoad;
- (void)viewWillAppear:(BOOL)animated;
- (void)viewDidAppear:(BOOL)animated;
Avt
  • 16,927
  • 4
  • 52
  • 72
1

init is called before viewDidLoad and most UI components will not be available in init. Use this to initialise variables, arrays etc.. Anything which is not going to require any UI component calls.

viewDidLoad means the view has been loaded and UI components are available to set things on, for example, set the value in a text field.

So you should be setting up the image view, caption label and gesture recognisers in viewDidLoad not in init.

Duncan Groenewald
  • 8,496
  • 6
  • 41
  • 76