Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use lazy instantiation in iOS?

I've heard that lazy instantiation of objects in iOS is pretty common, however I'm not exactly sure when I should use it? Could someone give a brief explanation of when I should use lazy instantiation and when I should just initialize my properties in the init method?

My concern regarding lazy instantiation is that it requires a lot of code (compared with just writing it all in the init method), especially if you have multiple properties to initialize.

like image 409
Nosrettap Avatar asked May 24 '12 14:05

Nosrettap


People also ask

When would you use a lazy property?

Lazy properties are also useful when the initial value for a property requires complex or computationally expensive setup that shouldn't be performed unless or until it's needed. The example below uses a lazy stored property to avoid unnecessary initialization of a complex class.

Why should I use lazy initialization?

Lazy initialization of an object means that its creation is deferred until it is first used. (For this topic, the terms lazy initialization and lazy instantiation are synonymous.) Lazy initialization is primarily used to improve performance, avoid wasteful computation, and reduce program memory requirements.

When should I use lazy var Swift?

Lazy variables allow you to delay the initialisation of stored properties. This can be useful to only perform expensive work when it's actually needed. The different between lazy- and computed properties is important in cases you need to have calculations based on the current state of values.

What do you mean by lazy property in IOS?

A lazy stored property is a property whose initial value is not calculated until the first time it is used. You indicate a lazy stored property by writing the lazy modifier before its declaration.


1 Answers

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.

like image 188
Paul.s Avatar answered Nov 11 '22 11:11

Paul.s