Why is assigned a nil to singleton's static variable

房东的猫 提交于 2019-12-22 06:36:44

问题


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.


回答1:


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




回答2:


Because if you dont ask, you gonna initiatlite "*sp" any time you call the "sharedPainter", losing any data.

So, if you ask if sp is nil and the answer is FALSE means "sp" is already initialized and it return the instance. If the answer is true, that means that sp is not initialized and just in that case you call the init function.



来源:https://stackoverflow.com/questions/13614692/why-is-assigned-a-nil-to-singletons-static-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!