1

I am creating a calculator for some cards game. In that game, I am creating a Singleton class to manager the game. It holds the scores, keeps track of where the game is etc...

Now after the app launches, I will ask the user to enter 4 players' names. After that, 4 player objects are instantiated according to their names. I already have an object called "Player", so 4 players will get instantiated with their name, and a score of 0 to start with.

Now I need to store those players in my singleton class. Therefore, I created 4 Player properties in the class. However my question is, under the init method in the Singleton class, in:

if ((self = [super init])) {
    // set properties here
}

Where // set properties here is, what do I write? Do I have to do anything with the Players properties over there?

Thank you,

darksky
  • 20,411
  • 61
  • 165
  • 254

3 Answers3

1

You don't need to do anything except return the shared instance. Usually the singleton's properties are set in whatever class your instantiating it from.

ennuikiller
  • 46,381
  • 14
  • 112
  • 137
0

No, you aren't required to do anything with them, although I would probably set them to nil.

FreeAsInBeer
  • 12,937
  • 5
  • 50
  • 82
  • Since I synthesized those players, in other classes I can do something like: mySingletonClass.player1 = player1 true? – darksky Jul 15 '11 at 14:00
  • You could. The syntax will be more like `[SingletonClass sharedInstance].player1 = player1`. Of course don't forget to release the variable in your other class to prevent a memory leak. – FreeAsInBeer Jul 15 '11 at 14:09
0

Maybe I'm wrong, but doesn't your AppDelegate already serve as a Singleton?

Man of One Way
  • 3,904
  • 1
  • 26
  • 41
  • 1
    Hmm.. I think you can say that. But it is bad design to let your AppDelegate manage things like what I want it to manage. – darksky Jul 15 '11 at 13:59
  • 1
    I agree with Nayefc here. Many new iOS programmers let their App Delegate run code that should be in several different classes. Usually it's good to stick with the idea that each class has it's own function instead of creating an Abomination class that handles everything. Logically separating your code makes it easier to understand what class runs what code, making it easier to maintain, and easier to change. – FreeAsInBeer Jul 15 '11 at 14:07
  • Thanks for the added detail @FreeAsInBeer. Furthermore, Cocoa Touch heavily relies on MVC and object oriented programming which is all about separation. A separate class which keeps track of the game, and sort of manages it, is the best way to go. – darksky Jul 15 '11 at 14:15
  • 1
    I've posted a question regarding the Singleton and Appdelegate design, http://stackoverflow.com/questions/6708250/is-it-a-bad-practice-to-use-your-appdelegate-as-your-singleton to discuss it more deeply. – Man of One Way Jul 15 '11 at 14:19