tags:

views:

41

answers:

2
@implementation MySingletonClass
static MySingletonClass *sharedInstance = nil;


+ (MySingletonClass*)sharedInstance {
    @synchronized(self) {
        if (sharedInstance == nil) {
            sharedInstance = [[self alloc] init];
        }
    }
    return sharedInstance;
}

+ (id)alloc {
    @synchronized(self) {
        if (sharedInstance == nil) {
            sharedInstance = [super alloc];
            return sharedInstance; 
        }
    }
    return nil; 
}

+ (id)allocWithZone:(NSZone *)zone {
    @synchronized(self) {
        if (sharedInstance == nil) {
            sharedInstance = [super allocWithZone:zone];
            return sharedInstance; 
        }
    }
    return nil; 
}

-(id)init {
    self = [super init];
    if (self != nil) {
        // initialize stuff here
    }

    return self;
}

@end

Not sure if it's ok to overwrite both alloc and allocWithZone: like this...?

A: 

You don't need to override alloc because the default implementation calls allocWithZone:

Other than that, you probably need to override some other methods. See the Apple docs for details.

JeremyP
A: 

Take a look at this Singleton template. I've used it (once, ha ha! get the joke) and it has worked very well.

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

John Smith