2011/12/11

Objective-C Singleton Class

Singleton class is really awesome when I need to share some data throughout many places. If I use normal way which is passing object pointer around, I have to care about a lot of object assigning tasks. With singleton class, it is really simple to use shared class object.

  • no instanciation
  • one class method do the all necessary job
  • first time of the class method call > create single instance
  • other class method calls > return already created instance
  • how to use?
    • include singleton class's header file
    • use class method to obtain class instance

Sample Class's header file
@interface SampleClass : NSObject

+ (SampleClass*)sharedInstance;

@end

Sample Class's source file
@implementation SampleClass

static SampleClass *sharedInstance = nil;   // shared instance

+ (SampleClass*)sharedInstance
{
    @synchronized(self)
    {
        if (sharedInstance == nil)
            sharedInstance = [[super allocWithZone:nil] init];

        return sharedInstance;
    }
}

+ (id)allocWithZone:(NSZone*)zone
{
    return [[self sharedInstance] retain];
}

- (id)copyWithZone:(NSZone*)zone
{
    return self;
}

- (id)retain
{
    return self;
}

- (NSUInteger)retainCount
{
    return NSUIntegerMax;  // object cannot be released
}

- (oneway void)release
{
    // do nothing
}

- (id)autorelease
{
    return self;
}

No comments:

Post a Comment

Labels

Followers