为什么为单例的静态变量分配了一个 nil [英] Why is assigned a nil to singleton's static variable

查看:35
本文介绍了为什么为单例的静态变量分配了一个 nil的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用这个有什么好处:

+ (CardPainter*) sharedPainter {
    static CardPainter* sp = nil;

    if (nil == sp) {
        sp = [[CardPainter alloc] init];
    }

    return sp;
}

而不是这个:

+ (CardPainter*) sharedPainter {
    static CardPainter* sp = [[CardPainter alloc] init];

    return sp;
}

静态变量初始化只执行一次,所以我看不到前者的优势.

The static variable initialization is performed only once, so I see no advantage of the former.

推荐答案

嗯,在编译器级别有几个重叠的原因……最简单的考虑是静态变量存储在已编译应用程序的专用数据部分中,这只是按原样映射到内存中.所以编译器必须在编译时准确地知道那是什么.根据定义和实践,任何 Objective-C 方法调用的结果在编译时都是不可预测的 - 您永远无法确定在运行时不会发生有趣"的事情来改变该方法调用的行为,因此您不会确定会返回什么.

Well, at a compiler level there's several overlapping reasons… the simplest to think about is that static variables are stored in a dedicated data section of your compiled application, which is just mapped into memory as-is. So the compiler has to know precisely what that is at compile time. The result of any Objective-C method call is unpredictable at compile time by definition and in practice - you never know for sure that something "interesting" won't happen at runtime to change the behaviour of that method call, so you don't know for sure what will be returned.

这与 e.g. 有点不同.C++,出于各种原因(一个关键是 C++ 有构造函数,而 Objective-C 没有).但即使在 C++ 中,由于以下几个原因,它仍然不受欢迎:

This is all a bit different from e.g. C++, for various reasons (a key one being that C++ has constructors, whereas Objective-C does not). But even in C++ it's still frowned upon for several reasons:

  1. 构造函数顺序是不可预测的,但构造函数相互依赖很容易也很常见,这意味着您的程序在运行时可能有未定义的行为(包括数据损坏或崩溃).
  2. 初始化大量非平凡对象的成本可能很高.在启动时一起做这一切可能会很有效,但它会使您的应用启动缓慢,这更糟糕.

后一点同样适用于 Objective-C.您在启动时避免做的事情越多,而是及时、按需做,通常用户体验就越好.

The latter point applies equally to Objective-C. The more you can avoid doing at launch time, and instead do just-in-time, on-demand, the better the user experience generally is.

[ 请注意,无静态对象实例"规则有一个值得注意的例外,那就是@foo"形式的字符串.这些实际上在您的应用程序的数据部分中编码为真实实例(特殊 NSString 子类的),它们在启动时被映射并神奇地按原样工作.但这是非常仔细的架构和编译器 &运行时在这方面紧密耦合,以确保一切顺利.它没有也不能普遍适用.]

[ Note that there is one noteable exception to the "no static object instances" rule, and that's strings, of the @"foo" form. Those are actually encoded in your app's data section as real instances (of a special NSString subclass) that just get mapped in at launch and magically work as-is. But that's very carefully architected and the compiler & runtime are tightly coupled on that aspect, to make sure it all works smoothly. It doesn't and cannot apply generally. ]

这篇关于为什么为单例的静态变量分配了一个 nil的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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