18

Is there a BOOL or some other way of knowing if viewDidLoad: has been called?

I need to change a view property every time my view has entered active, but if the view hasn't ever been loaded, I don't want to prematurely trigger viewDidLoad:. If there isn't way of easily telling if viewDidLoad: has been called, I'll simply add a BOOL called loaded set to NO in the view controller init, then change the view properties after entered active if loaded is YES or in viewWillAppear: if loaded is NO then set loaded to YES.

kev
  • 7,712
  • 11
  • 30
  • 41

3 Answers3

63

Use isViewLoaded. Other than that it does exactly what you want, there's not that much to say about it. The documentation is as simple as:

Calling this method reports whether the view is loaded. Unlike the view property, it does not attempt to load the view if it is not already in memory.

Tommy
  • 99,986
  • 12
  • 185
  • 204
1

Perhaps you should init your UIView in viewDidLoad, and then change it in whichever way you need to inside viewWillLayoutSubviews.

Andrew
  • 7,693
  • 11
  • 43
  • 81
1

Here's the pedantic answer to this question. If you want to know when viewDidLoad has been triggered, you have to implement viewDidLoad in your view controller

- (void)viewDidLoad
{
    [super viewDidLoad];

    viewDidLoadCalled = YES; // Not actually the best way to do this...
    // Set up more view properties
}

But as Tommy says, you actually need to use isViewLoaded. This gets around the problem of doing a check like

if (!self.view) {
    // do something
}

which inadvertently loads the view by virtue of asking about it.

Be aware that by the time viewWillAppear: is called, the view will always have loaded. Also, on older (pre-iOS 6 I think) releases, the view can unload and be reloaded many times over a view controller's lifetime. Refer to the very nice Big Nerd Ranch view lifecycle diagram for the old behavior. It's almost the same in iOS 6+, except that the view doesn't unload under low memory conditions and viewDidUnload doesn't get called:

enter image description here

nevan king
  • 112,709
  • 45
  • 203
  • 241