单例目标澄清 [英] Singleton objective c clarification

查看:63
本文介绍了单例目标澄清的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我继续学习的过程中,这本书实现了单例. 我了解使用它的原因,但我只想对代码进行一些说明.

as I continue my studies the book implemented a singleton. I understood the reason why use it but I just wanted some clarification regarding the code.

+ (BNRItemStore *)defaultStore
{
    static BNRItemStore *defaultStore = nil;
    if(!defaultStore)
        defaultStore = [[super allocWithZone:nil] init];

    return defaultStore;
}

static BNRItemStore * defaultStore = nil;行中直到return语句. 我的问题是;在我一直在另一个类或应用程序的一部分中调用该类([[BNRItemStore defaultStore] someMethod];)的所有时间中,defaultStore变量将设置为nil吗?

In the line static BNRItemStore * defaultStore = nil; until the return statement. My question is; all the time that I call this class, [[BNRItemStore defaultStore] someMethod]; in another class or part of the app, the defaultStore variable will be set to nil?

欢呼

推荐答案

重要的是要理解static关键字有两个作用.一个原因是它使该变量在调用该方法之前存在,并在返回该方法之后保持不变,以便在下一次调用时可以使用.另一个效果更加微妙-初始化静态变量的赋值"是在加载代码时执行的,而不是在调用方法时执行的.因此,它不会在每次调用时都重新初始化.

It's important to understand that the static keyword has two effects. One is that it makes that variable exist before the method is called, and persist after it returns, so that it will be available for the next call. The other effect is more subtle -- the "assignment" that initializes the static variable is executed when the code is loaded, not when the method is called. So it does not get reinitialized on every call.

但是由于变量存在于方法的外部",因此它的名称应该是唯一的-请勿在此类的另一个单例中使用相同的名称.

But since the variable exists "outside" of the method, it's name should be unique -- don't use the same name in another singleton in this class or another one.

这篇关于单例目标澄清的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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