Why is it assigned a static variable nil to singleton

What is the advantage of using this:

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

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

    return sp;

instead of this:

+ (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.

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.

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. Constructor order is unpredictable, but it’s easy and common to have constructors depend on each other, meaning your program can have undefined behaviour at runtime (including data corruption or crashing).
  2. Initialisation of lots of non-trivial objects can be expensive. Doing it all together at launch time might be efficient, but it makes your app slow to launch, which is far worse.

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.

[ 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. ]

Hello, buddy!稿源:Hello, buddy! (源链) | 关于 | 阅读提示

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 移动开发 » Why is it assigned a static variable nil to singleton

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录