views:

579

answers:

1

I already had a question like this, but I already deleted it anyway.

I have very simple app that has a root view controller and it switches between two other view controller views. So in my root view controller, It lazy loads the instances of the two other view controllers. Each time the switch button in the toolbar is pressed, the current view controller being displayed (its view) is unloaded (set to nil), and the new one is loaded and added to the subview.

Since I load my view controllers and unload at specific times, the lazy loading code being in the getters is very confusing because I don't actually want to load them right when I use them, I need to load them before so the flip animation will look good. So I think I want to make loadFirstVC and loadSecondVC methods to load the view controllers. Is this a good idea?

+2  A: 

The main reason for lazy-loading is NOT to defer loading that will definitely occur. It is for deferring loading that may never be needed. (It's also good for forcing reloads when the data has changed, but that's not your issue here.)

Example: Let's say you have a bunch of data about a person, including a photo, which is stored in an external file. But the photo will only be displayed if the user goes to a subview, so why load the photo from its file until you know for sure that the subview is going to appear? Boom, use lazy loading.

By the time you KNOW you want to load a certain piece of data, it's unlikely to matter very much when exactly you load it.

When does it matter? Well, that's really a matter of optimization. There's a saying you may have run across; if you haven't, this is as good a time as any: "Premature optimization is the root of all (programming) evil."

So ask yourself two questions:

  1. Will the piece of data definitely be needed? If NO, proceed with the lazy-loading technique. If YES, go to question 2.

  2. Does it MATTER when I load the data? [An example would be, it's huge and I don't want to load it until I've UNLOADED something else to make room for it] If NO, put it any place that works. If YES... Come back and ask us again, and provide more details.

...I suspect this doesn't answer your original question, but it sounds like you may be asking the wrong question in the first place. Apologies if I'm mistaken.

Amagrammer