Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
446 views
in Technique[技术] by (71.8m points)

objective c - 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.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...