0

In the application I'm currently working on, there's a case where I have 2 screens for a set of data: one is a list and one is a map. Each screen has its own view controller. The default screen is the list view, so that view controller loads first. But the other map screen view controller is also loaded and set up (as it encapsulates some geographic map-related data that the list screen view controller uses), even though the map screen is not visible yet.

I don't want the map screen view controller's nib and views to be loaded and initialized until the user switches to that screen, however.

Is there anything wrong with overriding the view property accessor within the map screen view controller as in the code below, and lazily loading/instantiating the nib? (The view property is not accessed until the map screen is about to be displayed, right before the map screen view controller's viewDidLoad method gets called.) I've tested that this works well, but I've never seen it done this way.

- (UIView *)view {
    if (!_view) {
        UINib *nib = [UINib nibWithNibName:@"MyNibName" bundle:nil];
        [nib instantiateWithOwner:self options:nil];
    }
    return _view;
}
smileyborg
  • 30,197
  • 11
  • 60
  • 73

1 Answers1

1

Figured out a better answer to this.

The code I'm working with isn't actually my own, and I hadn't noticed that the map screen's view controller wasn't actually a subclass of UIViewController, it was just subclassing NSObject (and adding its own view property).

By changing the map screen's view controller to actually inherit from UIViewController, and then using the designated initializer of initWithNibName:bundle:, the nib is by default lazily loaded/instantiated when the view property is accessed -- just like I was doing.

So, the answer to my question would be this: use the system frameworks and you won't even run into these issues! :) But it does seem to be the case that my code aligned with the actual best practice pattern; see Apple's guidelines and recommendations here.

Daij-Djan
  • 49,552
  • 17
  • 113
  • 135
smileyborg
  • 30,197
  • 11
  • 60
  • 73