Does this singleton pattern make sense?

Posted by dontWatchMyProfile on Stack Overflow See other posts from Stack Overflow or by dontWatchMyProfile
Published on 2010-06-17T09:20:13Z Indexed on 2010/06/17 9:23 UTC
Read the original article Hit count: 144

Filed under:
@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...?

© Stack Overflow or respective owner

Related posts about objective-c