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

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

问题描述

快速问题...好吧,我了解所有的属性在Objective-C中都以nil开始,并且向nil发送消息没有任何作用,因此您必须使用[[Class alloc] init]进行初始化;在向新创建的属性发送消息之前.但是,如果我不向该属性发送消息或使用self.property = something设置属性,该怎么办?在这些情况下,我还需要分配init吗?另外,UI属性是否也从零开始,例如您从情节提要中拖出的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很好地解释了不需要分配已经创建的初始化对象.

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属性.您可以在使用某种方法之前将它分配给init,但随后您必须担心该方法是否在我需要我的数组之前被调用?"或我会不小心再次调用它并重新初始化它."

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天全站免登陆