开发者

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开发者_如何学Python static, is the check unnecessary? Seeing code like this I always want to put an if (!sharedSomeObject) around the allocation.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜