何时在iOS中使用延迟实例化? [英] When to use lazy instantiation in iOS?

查看:99
本文介绍了何时在iOS中使用延迟实例化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我听说iOS中对象的懒惰实例很常见,但是我不确定何时应该使用它?有人可以简要解释我何时应该使用延迟实例化以及何时应该在init方法中初始化我的属性?

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?

我对懒惰实例化的关注是它需要很多代码(与在init方法中编写所有代码相比),特别是如果你有多个属性要初始化。

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.

推荐答案

详细说明我的评论。有时这种技术很好,如果你有一个只需要配置一次的对象,并且涉及一些你不想让你的init方法混乱的配置。

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;
}

这是一个非常人为的例子,但你可以开始看到它的优点。方法应该像类一样,做好一件事。这种方法碰巧返回我想要的roundedView。如果我把这个代码打到init方法中,那么init方法现在必须知道如何实例化和配置这个视图以及我在那里拍摄的任何其他对象的细节。

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.

这篇关于何时在iOS中使用延迟实例化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆