Why set sharedStore to nil?


#1

Hi all,

I’m going through chapter 8, and I am struggling to understand how the sharedStore method works.

The idea is that this is a persistent object. Once it is created, there will be a single instance that is shared by any objects that want to interact with it, correct?

So how does this method accomplish that?

Here is the code we’re using:

+ (instancetype) sharedStore
{
    static BNRItemStore *sharedStore = nil;

    if (!sharedStore) {
         sharedStore = [[self alloc] initPrivate];
    }

    return sharedStore;
}

Why do we have that first line? We’re declaring a BNRItemStore, and then setting it to nil. Then we’re checking if it’s nil, and if it is, we’re allocating and initializing it.

But lets say there’s already a BNRItemStore created, and now another method tries to call this. Won’t that then erase the original instance by setting it to nil, then create a new one? Is it the term “static” that prevents this somehow?


#2

Yes, you got it.

When you look at a piece of code, it is not always the case that what you see is what you get unless you are aware of the rules of the language (C in this case.)

To understand what’s going on there, you need to know how static affects the declaration of a variable.

A variable declared as static, inside the body of a function, gets initialised only once and maintains its value until it is reassigned a new value.

[Become a competent programmer faster than you can imagine: pretty-function.org]