memmons
memmons

Reputation: 40502

iPhone SDK: When allocating a static variable, should I check for nil?

I often see singleton classes designed similar to the following:

@implementation SomeImplementation

static SomeClass *sharedSomeObject = nil;

+ (void) someClassMethod {
   sharedSomeObject = [[SomeImplementation alloc] init];
   // do something
}

@end

someClassMethod can be called at any time -- should it be checking for nil first before allocating a new instance of sharedSomeObject? Or, since sharedSomeObject is static, is the check unnecessary? Seeing code like this I always want to put an if (!sharedSomeObject) around the allocation.

Upvotes: 0

Views: 995

Answers (2)

par
par

Reputation: 17724

Yes, absolutely! Otherwise you're creating more than one object every time your method is called. This is how we do things:

+ (SomeClass *) shared {
    static SomeClass    *sSingleton;

    if ( ! sSingleton ) sSingleton = [SomeClass new];

    return sSingleton;
}

EDIT

This answer is very old, not thread-safe, and no longer an appropriate singleton initialization method. See this Stackoverflow answer for the correct way of doing things nowadays with GCD.

Upvotes: 3

MatthiasC
MatthiasC

Reputation: 344

When it comes to the using the Singleton design pattern with Objective-C, I can highly recommend using Matt Galagher's "SynthesizeSingleton.h" macro. It deals with all the singelton-related topics like freeing (is that a proper word?) memory if the singleton will be no longer needed.

Here's the link to the "Cocoa with Love" website which contains an article on this topic as well as a link for the download of the "SynthesizeSingleton.h" header file:

http://cocoawithlove.com/2008/11/singletons-appdelegates-and-top-level.html

You will also find a discussion on using global variables vs. using the Singleton design pattern as well as some considerations on different approaches towards using Singletons there.

Upvotes: 2

Related Questions