Tutorial 1: The Singleton Class in Objective-C

Originally posted 30.11.2010

Okay then, I am going to jump right in and say: This is the most important class you will have in your game!

It saves you a lot of time with tracking game score, how many levels have been completed, what levels should be available, saving the game state and a lot of other things.

The great thing that takes a singleton class apart from a “regular” class, is the fact that you can only have one instance of a singleton class at any time in your program. This prevents data from being mixed up!

Basicly the way it works is, that the first time you try to create an instance of it, it actually does that. From then on, whenever you try to create an instance of your singleton class, the program automaticly creates a pointer to the first instance instead. Pretty brilliant!

Thats all for the introduction, this tutorial will not be going in to specific about how it works under the hood, but I will provide a complete set of code that works, that you can easily implement in your own project.

Be advised that I will not be talking memory management in this tutorial, that is something I will be looking at in detail in a later tutorial, so please do you self the favor and keep an eye out for when you need to release something.

Please do also note that I have the Cocos2d API installed.

Okay, so on with the code !

First you must create a new class, I have named mine “GameProgress” you can name yours what you like.

Start of by going in to GameProgress.h

Here you will want to tell the class what functions you will need it to handle. We want ours to handle the players progression so we will be needing 4 functions.

Under the @interface add the following:

+(GameProgress *)sharedGameProgress

-(void) setLevelsCompleted: (int) a;

-(void) setThisLevel: (int) b;

-(int) levelsCompleted;

-(int) thisLevel;

Thats it, now the implementation file knows what to expect!

Now go in to GameProgress.m

The first part will be the part that tells the class that it is a singleton class. Basicly what happens when you try to make an instance of it, is that the class checks if there is already an instance of it and if there is not, it creates one.

Modify it under the @implementation to look like this:

+(GameProgress *)sharedGameProgress

{

static GameProgress *sharedGameProgress;

@synchronized(self)

{

if (!sharedGameProgress)

sharedGameProgress = [[GameProgress alloc] init];

return sharedGameProgress;

}

}

Now you actually have a singleton class!

The way you can make it function to for example keep track of levels completed is by adding the following code, just under what you just added in the GameProgress.m file:

// declare the variables

int levelsCompleted;

int thisLevel;

/* First method checks if the current level is actually the

highest possible level the player can choose before setting the levelscompleted variable.

This method is called from my GameWon method in the GameController */

-(void) setLevelsCompleted: (int) a;{

if (thisLevel >= levelsCompleted)

levelsCompleted = a;

}

/* This method sets the current level, this method is called when the player selects a level from the menu */

-(void) setThisLevel: (int) b;{

thisLevel = b;

}

/* This method returns the levelsCompleted variable, this is made in to a method because it is impossible for other classes to diretly read a variable from another class. This method is called by the menu so it know how many levels it should make available to the player. */

-(int) levelsCompleted;{

return levelsCompleted;

}

/* This method returns the current level as an integer.

-(int) thisLevel;{

return thisLevel;

}

@end

I really hope this tutorial helped you out, this particular problem took me several hours to figure out, and at best I think the information out there is sparse.

oh, and in case you are wondering how to make an instance of the singleton class and how to call methods from it, inside another class, here is how:

/* this creates an instance or a pointer depending on if this is the first time you try to create it. Dont worry, the program figures this out for you! :) */

GameProgress *GameP = [GameProgress sharedGameProgress];

/* This calls a method inside the Singleton class, and please take notice that it always refers to the class and not the variable, even though they can have the same name */

[GameP levelsCompleted]; //returns levelsCompleted

//Here is how you set a variable from another class:

[GameP setThisLevel:1];

I hope you get the picture and that it was clearly explained.

As always if you have any questions or comments, Please leave them in the section below.

-Peter

If you enjoyed this tutorial, please support us by buying our released iOS game Up To The Top, it helps us to produce more content, thank you :)

  • http://www.myappventure.com Scott

    Thanks very much!

    -scott ruth

  • Pingback: Objective C: Passing NSDictionary from One Class to Another - Programmers Goodies

  • Peter

    You are very welcome, glad you liked it :)

  • Harshit

    best singleton tutorial ever seen

    • pixeleap

      Thank you Harshit, 
      We are happy that it was helpful! :)
      Please help us spread the word of our site in return :)

  • Sandeepmadhav2011

    worst site,iam  not understanding at all