May 24, 2012

Singleton Pattern in Objective-C (iOS) and release method (oneway) issue

Posted May 24, 2012
Apple gives a good sample on how to create a singleton class; I've modified it a bit for iOS programming:

static MyGizmoClass *sharedInstance = nil;

+ (MyGizmoClass*) sharedInstance
{
    if (sharedInstance == nil) {
        sharedInstance = [[super allocWithZone:NULL] 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;  //denotes an object that cannot be released
}

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

- (id)autorelease
{
    return self;
}


Modifications:
  1. Used "sharedInstance" method and variable name to make it easier to copy paste.
  2. - (void) release to - (oneway void) release
    The singleton sample produces a warning in the release method because NSObject uses the "oneway" return type modifier. It's basically an indication that the method is used for asynchronous messages. For more details on what oneway does, toodarkpark.net offers a good explanation.

No comments:

Post a Comment