Friday, February 4, 2011

Objective-C Semi-Singleton Class

Sometimes when building an iOS application, you will have a class you will want to access from anywhere. Such as, a controller with any number of child controllers (navigation, tab, etc.) and some of them need simple access back to the root controller.

Apple provides their own solution to creating a full-blown singleton class, but this can be a daunting task for a simple need. A semi-singleton is much easier to create but has two caveats:

1) semi-singletons only work if there is ever only one instance of the class
2) the singleton cannot be used to initialize itself

So, here is how to make a simple "HelloWorld" class into a semi-singleton.

In the HelloWorld.m file, create a static property to hold the singleton instance:


// put just after @implementation line
static HelloWorld* helloWorldInstance;


in the init method, assign the instance (self) to the static property:


-(id) init
{
if ((self = [super init]))
{
// assign the semi-singleton
helloWorldInstance = self;
// do other init stuff here ...
}
return self;
}


create the shared static method for accessing the semi-singleton:


+(HelloWorld*) sharedInstance {
return helloWorldInstance;
}


Lastly, be sure to dealloc the property to avoid crashes:


-(void) dealloc
{
helloWorldInstance = nil;
[super dealloc];
}


And now from any class, we can access a pointer to the instance:


#import HelloWorld.h

HelloWorld *helloWorld = [HelloWorld sharedInstance];


And there you have it. Thanks to Steffen Itterheim and his book about cocos2d programming for the original tip!

1 comment:

Unknown said...

Basecamp PHP API

I have tried to use this and cannot. I have used the sample code and there is simply no output from that block of code. I am completely unfamiliar with curl and so it is difficult for me right now, to test for errors, connection, etc... I have looked through the code and it is written beautifully, just wish I could use it. I have all required extensions there just simply seems to be no access through the constructor.