-1

I'm reading through a book trying to brush the dust off of Objective-C, and I ran into this question while reading how to implement a singleton. This is the implementation as they have it in the book:

+ (ClassName *)sharedClass {
static ClassName *sharedClass = nil;
if (!sharedClass) {
sharedClass = [[super allocWithZone:nil] init];

return shared store

}

My question is, why would they set it to nil each time the method is ran, then check if it's nil, which it now obviously is, and create a new instance? That sounds like it defeats the whole purpose of a singleton, to only have one instance of a class. I've noticed a ton of questions related to singleton implementation, but none specific to this aspect of it. Believe me, I combed through before posting.

Henry F
  • 4,960
  • 11
  • 55
  • 98
  • Better read-up on static variables in functions. – zaph Feb 24 '15 at 00:03
  • 1
    since the var is declared static, think of it as a variable at the file level. the = nil runs only initially. anyway, there's a very good singleton solution here http://stackoverflow.com/questions/7568935/how-do-i-implement-an-objective-c-singleton-that-is-compatible-with-arc – danh Feb 24 '15 at 00:04
  • @Zaph Do they not get set to nil when you set them to nil? – Henry F Feb 24 '15 at 00:34
  • Knowing the "C" language is worthwhile, I've read the book more than once, tl;dr only get's one so far. The answer is it is set to nil only once due to the declaration. Static variables in "C" have different rules depending on the scope that are in. Objective **is** "C" plus extensions. – zaph Feb 24 '15 at 01:32

1 Answers1

1

The static variable is set to nil only for the first time. Once the sharedClass instance is instantiated, you will alway have the same instance whenever you invoke [ClassName sharedClass].

You should use thread-safe pattern to use singleton pattern.

+ (instancetype)shared {
    static id shared = nil;

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        shared = [[self alloc] init];
    });
    return sharedInstance;
}

This will prevent possible crashes.

Ryan
  • 4,799
  • 1
  • 29
  • 56