Singleton objective c clarification

前端 未结 5 905
青春惊慌失措
青春惊慌失措 2020-12-12 02:18

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.

+ (BN         


        
相关标签:
5条回答
  • 2020-12-12 02:32

    For function-static variables the line

    static BNRItemStore *defaultStore = nil;
    

    is not an assignment. Rather, it is static initialization, which happens only once - the first time the code goes through your function. In subsequent invocations the value will not be nil, because you assign a non-nil value to it.

    Your implementation is safe in single-threaded environments. For concurrent environments you would need to add some form of synchronization.

    0 讨论(0)
  • 2020-12-12 02:46

    Static variables are initialized just the one time when the function/method is first called. After that, you can basically pretend the line doesn't exist.

    0 讨论(0)
  • 2020-12-12 02:47

    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.

    0 讨论(0)
  • 2020-12-12 02:50

    Apple recommends something like the following

    + (BNRItemStore *)defaultStore
    {
        static BNRItemStore *defaultStore = nil;
        static dispatch_once_t done;
        dispatch_once(&done,
                      ^{ defaultStore = [BNRItemStore alloc]init];});
        return defaultStore;
    }
    

    The above code assumes ARC - If not using ARC you would have to define do nothing retain, release, autorelease, and dealloc methods.

    0 讨论(0)
  • 2020-12-12 02:51

    That's the initializer of a variable with static storage duration. The value will be set when the executable is loaded into memory.

    Note that its not necessary to explicitly set the value to nil as all variables with static storage duration are automatically set to 0.

    0 讨论(0)
提交回复
热议问题