Browsing articles tagged with " singleton"

The Objective-C Singleton

Aug 30, 2009   //   by Derek van Vliet   //   Development  //  33 Comments

One of the most useful patterns that we have employed in our iPhone game is the singleton. For those who don’t know, singletons are a class that only gets instantiated once in your application’s run-time. They often take the form of manager or factory classes. A good example of a singleton is the web-based resource manager class that we posted about recently.

We have been using singletons for a variety of things in our cocos2d-based game. Including:

  • Resource management
  • Atlas sprite managers
  • User settings management
  • Score management

Below is a template for the singletons that we use in objective-c.

MySingleton.h:

#import <Foundation/Foundation.h>
 
@interface MySingleton : NSObject {
 
}
+(MySingleton*)sharedMySingleton;
-(void)sayHello;
@end

MySingleton.m:

@implementation MySingleton
static MySingleton* _sharedMySingleton = nil;
 
+(MySingleton*)sharedMySingleton
{
	@synchronized([MySingleton class])
	{
		if (!_sharedMySingleton)
			[[self alloc] init];
 
		return _sharedMySingleton;
	}
 
	return nil;
}
 
+(id)alloc
{
	@synchronized([MySingleton class])
	{
		NSAssert(_sharedMySingleton == nil, @"Attempted to allocate a second instance of a singleton.");
		_sharedMySingleton = [super alloc];
		return _sharedMySingleton;
	}
 
	return nil;
}
 
-(id)init {
	self = [super init];
	if (self != nil) {
		// initialize stuff here
	}
 
	return self;
}
 
-(void)sayHello {
	NSLog(@"Hello World!");
}
@end

Example Usage

Using the methods of the singleton is then as easy as this:

[[MySingleton sharedMySingleton] sayHello];

Our Games

Latest Tweets