iPhone Game Programming – Tutorial 7 – Singleton Class

This is a small tutorial on how to create and use a Singleton class. Whilst I’ve been creating these tutorials it has become clear that managing state is important in your game. The ability to manage both the OpenGL state locally and also any state related to your game is a key building block for a game.

The Singleton pattern is a design pattern that is used to restrict the number of instantiations of a class to just one object. For our purposes we are going to use it to control state information we want to make global and share throughout our game, or at least available to other objects which want to get state information.

This tutorial covers the creation of a simple Singleton class and how it is implemented to provide state control of the currently bound OpenGL texture. I will be using this Singleton class in coming tutorials to help manage any state which is why I’ve done this tutorial to get the concept introduced.

As usual, all feedback and comments are welcome and links for both can be found below.

Tutorial 7 (26:14)

Tutorial 7 Project

Mike

Discuss in our community forum.

Share:
  • Digg
  • del.icio.us
  • Facebook
  • MySpace
  • Reddit
  • StumbleUpon
  • Technorati
  • TwitThis
  • Design Float
  • DZone
  • email
  • Google Bookmarks
  • LinkedIn
  • Scoopeo
  • Tumblr

28 Comments

uprise78  on May 15th, 2009

Thanks for the continued tutorials. One little thing you may want to consider is your singleton implementation. There are quite a few issues with it and I highly recommend you check out and consider using a proven Cocoa singleton boilerplate such as http://www.google.com/codesear.....ox-for-mac\.googlecode\.com&l=22.

uprise78  on May 15th, 2009

That link got mangled. Try this: http://bit.ly/4QstA

mike  on May 15th, 2009

Hi uprise78 and thanks for the feedback. When I was researching the Singleton pattern in Objective-C there seemed to be several different ways of doing it. Some people seemed to do what I have covered in the tutorial and keep it very basic and others went further and included the extra code which is in the Macro you have linked.

I decided to keep it simple for this tutorial, but your completely right that it could be more complete but adding in the allocWithZone, copyWithZone, retain and retainCount methods. I did mention in the tutorial that there was more which could be done within the Singleton and what I’ll do is cover the missing elements in the next tutorial just to make sure people have the more complete implementation.

Based on your experience, if the developer knows that the class is a singleton etc, what is the biggest issue with just having the basics in the one I’ve done.

Thanks again for the feedback. Its this kind of discussion which has helped me push my knowledge forward and will help others reading this blog.

Mike

mike  on May 16th, 2009

More information on creating a singleton from Apple can be found at the following link

http://tiny.cc/NPM9Y

The following code can be used to replace ALL the code in the SingletonGameState.m file and provides the full Singleton implementation.

//
//  SharedGameState.m
//  Tutorial1
//
//  Created by Michael Daley on 03/05/2009.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "SingletonGameState.h"

@implementation SingletonGameState

@synthesize currentlyBoundTexture;

// This var will hold our Singleton class instance that will be handed to anyone who asks for it
static SingletonGameState *sharedGameStateInstance = nil;

// Class method which provides access to the shareGameStateInstance var.
+ (SingletonGameState *)sharedGameStateInstance {

	// synchronized is used to lock the object and handle multiple threads accessing this method at
	// the same time
	@synchronized(self) {

		// If the sharedGameStateInstance var is nil then we need to allocate it.
		if(sharedGameStateInstance == nil) {
			// Allocate and initialize an instance of this class
			[[self alloc] init];
		}
	}

	// Return the sharedGameStateInstance
	return sharedGameStateInstance;
}

// This is called when you alloc an object.  To protect against instances of this class being
// allocated outside of the sharedGameStateInstance method, this method checks to make sure
// that the sharedGameStateInstance is nil before allocating and initializing it.  If it is not
// nil then nil is returned and the instance would need to be obtained through the sharedGameStateInstance method
+ (id)allocWithZone:(NSZone *)zone {
    @synchronized(self) {
        if (sharedGameStateInstance == nil) {
            sharedGameStateInstance = [super allocWithZone:zone];
            return sharedGameStateInstance;  // assignment and return on first allocation
        }
    }
    return nil; //on subsequent allocation attempts return nil
}

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

- (id)retain {
    return self;
}

- (unsigned)retainCount {
    return UINT_MAX;  //denotes an object that cannot be released
} 

- (void)release {
    //do nothing
}

- (id)autorelease {
    return self;
}

@end

Mike

Jamie Hill  on May 16th, 2009

Mike, great summary. Any singleton examples in Objective-C have been way too complicated for most cases.

One change I would make it to not call the glXXX methods in the rest of your code and instead call these in the singleton i.e. the setCurrentlyBoundTexture would also take the GL_TEXTURE_2D constant:

[TheSingleton setCurrentlyBoundTexture: texture type: GL_TEXTURE_2D]

That way it removes any duplication, moves the logic into the singleton and it act as an adapter (I am quite fond of the adaptor pattern when it comes to external libraries such as OpenGL). You could eventually move all OpenGL calls to the singleton meaning other than the singleton itself, no other code even needs to know that you are using OpenGL.

mike  on May 16th, 2009

Hi Jamie and thanks for that feedback. I had not got that far ahead in my thinking about abstracting the OpenGL calls into the Singleton as well. I can see how that would keep things clean, and given I’m thinking through the whole scene manager concept at the moment to handle the rendering of multiple entities, having a single place like that would be handy.

I’ll have a play and see what I come up with :o)

Mike

bob  on May 16th, 2009

@Mike
Thanks Mike, another good tutorial. Hi Jamie, that’s a good idea about moving the openGL calls to the Singleton.
I saw some code where they created a texture factory for the singleton and they used an NSMutableDictionary to keep tract of the textures.
They had it so you could add,remove and flush all textures. I thought that was an interesting concept.

mike  on May 16th, 2009

Thanks bob. I’m just creating a resource manager myself using the singleton pattern. At the moment I’m using NSMutableArrays though as I’ve found that looking up keys in a dictionary inside the AngleCodeFont class for the kerning seems to be very expensive on the CPU.

I’m not sure if others have had the same experience?

At the moment I’m playing with the idea that you can ask the resource manager to create a sprite sheet for you and pass back a reference you can use from then on to grab that sprite sheet from the resource manager. You just pass in the image name and normal sprite sheet details and it does the creation and storage for you.

The reference being passed back at the moment is just the index the sprite sheet is given in the mutable array so looking it up is quick when someone requests a sprite sheet using that reference number. This needs a little more thought as if a sprite sheet was removed from the array, then all the references for the other entires change :o). Using a dictionary with a key would be good but I’m not sure what the performance is like. I’ll have to have a play and try it out.

If anyone has played in this area and has any comments it would be good to hear.

Mike

bob  on May 16th, 2009

@Mike
Hi Mike , take a look at this. He hasn’t posted part2 yet but I’ll be interested to see what he’s doing.

http://playingwithcode.com/blog/?p=179#more-179

mike  on May 17th, 2009

Nice find bob. Its good to see some other easy to follow OpenGL examples on the iPhone. It looks like the project could be an interesting one as well so I’m going to be following it too :o)

Mike

Kenan  on May 17th, 2009

Thanks guys for this great tutorial!

TydzieÅ„ z programowaniem dla iPhone | appledev.pl  on May 17th, 2009

[...] – Tutorial 7 – Singleton Class W 7 części tutoriala autor przedstawia sposób korzystania ze wzorca Singleton przy projektowaniu [...]

Thomas  on May 19th, 2009

I just found your blog, and have to say it is brilliant, i have watch a few movies now and i don’t even have a mac yet :)

Are you gonna make tutorials on how to check where the user tabs on the screen and stuff like game menu?

mike  on May 19th, 2009

Hi Thomas and thanks for your comment.

There are a number of tutorials on my list which include:

- Particle System
- The cocoa touch API and accelerometer
- Creating menus and preferences
- Collision detection
- Sound

The one I’m working on is the Particle System and I’m then planning on getting the sound one out of the way. Once that is done along with some project refactoring I’ll then be able to start an actual game using this code which will then include Collision detection and menus etc

I’ve had some great suggestions for some changes to current classes such as animation which I’ll also be looking into, its just getting the time really :O) so you will certainly be seeing more tutorials being posted.

Mike

Thomas  on May 19th, 2009

Thanks for your quick reply, it sounds great with more tutorials i can’t wait :) But great work, and by far then best tutorial to iphone game i have found yet.

Peter  on May 19th, 2009

Hi Mike,

I wanted to start off by saying you deserve a medal for putting all this together. Fantastic job!!

I have made it up to the 6th tutorial so far and find them incredibly fascinating and educational. I am however at a head scratching point.

It appears that the Image class has been designed without any real mechanisms for determining and setting it’s current position other than renderAtPoint. When you get into collision detection is this a class you will be updating to include this as well as tracking it’s bouding box or am I daft and have missed that functionality all together.

Thanks for all the great work.

mike  on May 19th, 2009

Hi Peter and thanks for the feedback :o)

You’ve not missed anything. There is nothing specific in the Image class to handle collision detection. My plan is to have the image separate from any bounding geometry so that you could have a bounding box which is maybe bigger or smaller than the image.

In my prototype which I use before getting tutorials ready, I’ve go an abstract class called AbstractEntity. This implements things such as position, velocity, state etc. Each specific game entity will then inherit from that class and implement the specific bounding geometry and collision detection needed for that specific entity. Part of this will be that it will have an image or Animation associated with it along with logic code. During the logic update each entity will be asked to update their logic and then within the render method each entity will be asked to render itself.

That’s what I’m playing with at the moment anyway :o)

I hope that makes sense, but if you have any questions just let me know and it will be covered in a tutorial ASAP.

Mike

Peter  on May 19th, 2009

Makes perfect sense and thanks so much for getting back to me so quickly.

Can’t wait to see what you have in store for us next!!

Thanks for all your hard work!

brad  on May 19th, 2009

Awesome job Mike, these tutorials have been a life saver so far after getting tossed into the world of Macs, the iPhone and Objective C overnight. Keep them coming!

mike  on May 24th, 2009

Thanks brad. Sounds like you have been given a steep learning curve. I hope the tutorials help reduce that slop as much as possible and post any questions you may have :o)

Mike

RoberRM  on May 28th, 2009

Hi Mike!

First of all, thanks for another excellent tutorial. ;)

And now a quick question: why is it that you do not deallocate the sharedGameStateInstance variable?

Maybe because there can only be one instance of this variable and, therefore, when you do [super dealloc] you are deallocating everything inside this class, sharedGameStateInstance included? But I’ve read everywhere that every time you allocate something you should deallocate it too…

In any case, if you did not intend to include this variable in the deallocation method, why rewrite it?

Thank you in advance for your answer. :)

Rober

MFerron  on June 15th, 2009

Hey Mike,

Thanks again for these tutorials. You’re doing me and everyone else a great service.

I’ve been following your tutorials and just now noticed you have a CGRect “screenBounds” in the EAGLView.h.

When was this implemented? How is this used? I’m not quite sure how I missed this.

Thanks for the help Mike.

Iphone Architect  on June 17th, 2009

thanks for this great tutorial, it would be nice to have a tutorial about mvc implementation for iphone apps

Incredible iPhone Game Programming Tutorials With Video | iPhone Development Tutorials and Tips  on July 31st, 2009

[...] 5 – Animation Class iPhone Game Programming – Tutorial 6 – Tiled Map Class iPhone Game Programming – Tutorial 7 – Singleton Class iPhone Game Programming – Tutorial 8 – Particle Emitter iPhone Game Programming – [...]

Kristian  on November 22nd, 2009

I’ve been using singleton’s quite happily since this tutorial, into I ran into a slight concern today.

The dealloc is never explicitly called, so my assumption was it happens by itself when its no longer in use, or maybe when the program shuts down. I was checking some cleanup code in the dealloc, and I realized that the debugger never seems to get there and the code never seems to run.

Should I be explicitly calling this at some point?
thanks!
-Kristian

mike  on November 23rd, 2009

Hi Kristian

I basically just create the dealloc in the singleton the same was as I would in any other class. Because my singletons should exist as long as the game is running I don’t explicitly call it, as I never want to remove the singleton.

When the game is done then everything just gets removed along with anything else that was still being used.

Hope that makes sense.

Mike

Day 29 – Game Preview « Creating Iphone Game with Cocos2d  on March 30th, 2010

[...] I learned how to create the Singleton Class mentioned in video from 71squared tutorial 7. [...]

Rob P  on May 21st, 2010

thanks mike, this got me on the right track to passing variables between XIBs! you rock

Leave a Comment