When to use lazy instantiation in iOS?

前端 未结 4 760
时光取名叫无心
时光取名叫无心 2020-12-12 23:05

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

4条回答
  •  青春惊慌失措
    2020-12-12 23:24

    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.

提交回复
热议问题