Question about initializing sharedStore to nil


#1

In this section there is the following block of code:

[code]+ (instancetype)sharedStore
{
static BNRItemStore *sharedStore = nil;
// Do I need to create a sharedStore?
if (!sharedStore)
{
sharedStore = [[self alloc] initPrivate];
}

return sharedStore;

}[/code]

In the explanation it states that only the first time that this method is called will a new instance of the BNRItemStore be created. During the first call, it will set the sharedStore pointer to nil, and then the if statement will execute since the sharedStore pointer is nil, returning a new BNRItemStore pointer.

It states that any subsequent calls to this method will return the same BNRItemStore instance that was already created instead of initializing a new one. How is this possible since on the first line of the method the sharedStore pointer is set to nil? Every time this method is called it appears as if the sharedStore value is set to nil, and since it is nil the if statement will always execute, returning a brand new instance of the BNRItemStore object.

The only explanation I can think of is that since the variable is static, the first line that sets the pointer to nil is ignored on subsequent calls. Is this true?


#2

Yes that’s certainly true. Because this variable is static it is initialised only once and hangs around until the application ends.


#3

This is something I stumbled across as well, and I have to say I am not 100% about this line too, I wonder if Christian could explain it in more detail (also in subsequent editions of the book) please?

Reading the code, I still do not understand why, when the class method sharedStore is called again, no new pointer is created and set to nil, then assigned to to the variable sharedStore again, making it forget about the previous value?

I suppose to me it would all make sense if the variable sharedStore was declared OUTSIDE the class method, making it a global variable, that is not re-defined every time the class method is called…


#4

I had the exact same question, which brought me here.

The following stack overflow post explains the concept quite nicely: stackoverflow.com/questions/8772 … o-nil-on-t


#5

Regardless of where they appear, static variables are literally static: they are created and initialised only once, and they stay around until the program terminates.

void FooBar ()
{
     long foo = 5;
     static long bar = 5;

     foo += 1;
     bar += 1;

     // foo is now 6
     // bar is now one more than what it was previously: bar == 5 + N
     // Where N (>=1) is the number of times FooBar is invoked.
}

Therefore they can be very useful, but they must be used with great care. Any function that relies on a static variable for its computation is not reentrant!

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