Objective-C/iPhone 开发中的延迟实例化 [英] Lazy instantiation in Objective-C/ iPhone development

查看:17
本文介绍了Objective-C/iPhone 开发中的延迟实例化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

快速问题...好吧,我知道在Objective-C中所有属性都以nil开始,并且向nil发送消息没有任何作用,因此您必须使用[[Class alloc] init]进行初始化;在向新创建的属性发送消息之前.但是,如果我不向该属性发送消息,或者我使用 self.property = something 设置该属性呢?在这些情况下我是否也需要 alloc init ?另外,UI 属性是否也从 nil 开始,例如从故事板中拖出的 UILabel 属性?这些需要 alloc init 吗?

Quick question... Well I understand that all properties start out as nil in Objective-C and that sending a message to nil does nothing, therefore you must initialize using [[Class alloc] init]; before sending a message to a newly created property. However, what about if I'm not sending messages to this property or if I set the property using self.property = something? Do I need to alloc init in these cases as well? Also, do UI properties start out as nil as well, such as a UILabel property that you drag out from your storyboard? Do these need alloc init?

感谢所有回答的人

推荐答案

Stunner 很好地解释了不需要分配已经创建的 init 对象.

Stunner did a good job of explaining not needing to alloc init objects that have already been created.

但是如果它是一个不存在的对象,你准备在哪里创建它?一个非常常见的模式,我提到它是因为你在你的帖子中提到了它,是惰性实例化.

But if it is an object that doesn't exist, where are you going to create it? A very common pattern, which I mention because you mentioned it in your post, is lazy instantiation.

所以你想要一个 NSMutableArray 属性.您可以在使用它之前在某个方法中分配初始化它,但是您必须担心在我需要我的数组之前是否调用了该方法?"或者我会不会不小心再次调用它并重新初始化它."

So you want an NSMutableArray property. You could alloc init it in some method before you use it, but then you have to worry about "does that method get called before I need my array?" or "am I going to call it again accidentally and re-initialize it."

因此,可以在属性的 getter 中进行故障保护.每次访问该属性时都会调用它.

So a failsafe place to do it is in the property's getter. It gets called every time you access the property.

.h
@property (nonatomic, strong) NSMutableArray* myArray;

.m
@synthesize myArray = _myArray;

- (NSMutableArray*)myArray
{
    if (!_myArray) {
        _myArray = [[NSMutableArray alloc] initWithCapacity:2];
    }
    return _myArray;
}

每次访问该属性时,它都会说:myArray 是否存在?如果不存在,则创建它.如果存在,只需返回我拥有的."

Every time you access that property, it says, "Does myArray exist? If not, create it. If it does, just return what I have."

此外,这种设计模式的一个额外好处是,您在需要资源之前不会创建资源,而不是一次性创建所有资源,例如,当您的视图控制器加载或应用程序启动时,这取决于需求,可以花几秒钟.

Plus an added benefit with this design pattern is you aren't creating resources until you need them, versus creating them all at once, say, when your view controller loads or your app launches, which, depending on the requirements, could take a couple seconds.

这篇关于Objective-C/iPhone 开发中的延迟实例化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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