When to use lazy instantiation in iOS? When to use lazy instantiation in iOS? ios ios

When to use lazy instantiation in iOS?


To elaborate on my comment. Sometimes this technique is good if you have an object that only needs to be configured once and has some configuration involved that you don't want to clutter your init method.

- (UIView *)myRoundedView;{    if (!_myRoundedView) {        _myRoundedView = [[UIView alloc] initWithFrame:<#some frame#>];        _myRoundedView.layer.cornerRadius = 10.f;        _myRoundedView.backgroundColor    = [UIColor colorWithWhite:0.f alpha:0.6f];        _myRoundedView.autoresizingMask   = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;    }    return _myRoundedView;}

It's a pretty contrived example but you can start to see the merit. Methods should be like classes and do one thing well. This method happens to return the roundedView I want. If I slapped this code into the init method then the init method would now have to know the nitty gritty details of how to instantiate and configure this view and any other objects that I slap in there.


It is good in situations where you have objects that can have a big memory footprint, so you can avoid to initialize all these expensive objects at the moment of the container class initialization. Lazy initialization can preserve memory consumption in several situations ...

However it is clear that if all the objects needs an initialization after or immediately after the container object initialization, lazy initialization doesn't make any sense and a standard constructor initialization should be used.

Lazy initialization should be used in case you have optional objects inside a class that could never be initialized during all class workflow .


As with any technique, there's not a single, one-size-fits-all rule to tell you when to lazily instantiate something. I think good advice is to use lazy instantiation for things that are expensive to instantiate. If something needs to do a lot of disk or network access, or takes a lot of CPU time to set up, you're better of deferring that work until it's actually necessary (or doing it in the background). Particularly for features that a user may or may not use, there's no sense wasting a lot of time in -init (or similar) setting things up, and doing so can contribute to making your application feel sluggish to the user.

With that said, you should avoid premature optimization. Don't spend a lot of time writing complicated code to help with performance until you've done things the obvious way, found a performance problem, and profiled your code to thoroughly understand the issue. After you've done that, you can start making changes to improve things.


matomo