Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
462 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...