Take the 2-minute tour ×

I've created a singleton (called sharedinstance) in my appDelegate, and ideally I want to access it from all other objects/instances in my code, but everytime I want to access a method/var in it, I'm having to do

Game *sharedInstance = [Game sharedInstance];

In whatever method in any other instance to be able to do something like..


I tried putting

Game *sharedInstance;

in the .h file of the other instance, but when I run the code, Game = 0. I just tried putting

Game *sharedInstance = [Game sharedInstance];

In the other instances init method but that's not helping either.

share|improve this question
add comment

closed as not constructive by vikingosegundo, Uwe Keim, Janak Nirmal, Jon Lin, sberry Oct 30 '12 at 7:59


3 Answers

up vote 2 down vote accepted

Your problem is not really related to singletons, it's just a matter of not knowing how to declare and use variables and methods. You need to get the instance of Game to call a method on it, you do this with [Game sharedInstance]. You then need to either call the method on it, or assign it to an instance variable to call a method later.

i.e. either:

[[Game sharedInstance] method]


(in the .h)
Game *sharedInstance

(in the init method in your .m)
sharedInstance = [Game sharedInstance];

(elsewhere in your .m)
[sharedInstance method];
share|improve this answer
add comment

In the Init method of your .m file use this

[[Game sharedInstance] method];
share|improve this answer
add comment

...everytime I want to access a method/var in it, I'm having to do...

Yes. Before you use an object, whether it's a shared object like a singleton or not, you have to get a reference to it. Calling your singleton's -sharedInstance method is one way to do that. Another option would be to declare a global variable that points to the singleton, but given that singletons are often used as a fancy substitute for global variables that seems like a poor idea.

share|improve this answer
add comment
