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.
+ (BNRItemStore *)defaultStore
{
static BNRItemStore *defaultStore = nil;
if(!defaultStore)
defaultStore = [[super allocWithZone:nil] init];
return defaultStore;
}
In the line static BNRItemStore * defaultStore = nil; until the return statement.
My question is; all the time that I call this class, [[BNRItemStore defaultStore] someMethod]; in another class or part of the app, the defaultStore variable will be set to nil?
Cheers
It’s important to understand that the
statickeyword 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.