Creating a global instance of an Object?

Discussion in 'iOS Programming' started by NickFalk, Mar 5, 2009.

  1. NickFalk macrumors 6502


    Jun 9, 2004
    OK I was thought in my youth that global variables is a crime against all that is holy. As I'm working my way through my less-than-epic Dungeon Crawler I am starting to think this might not be a 100% true:

    The main screen of my game is called dungeonView and is controlled by a dungeonViewController. I have created a player-object handling stuff like stamina, strength etc. as well as a few methods. I haven't really hit a brick wall or anything yet, but I find passing the Player Object instance around dungeonViewController's different methods fairly tedious, especially as there is never more than one instance of Player in existence.

    It has occurred to me that the existent of one global Player instance would be beneficial and I'm actually having a hard time finding any strong argument against this idea. Anyone disagrees? And if not, could anyone enlighten me on where I would init the instance? (Perhaps in the dungeonViewController's init-method?).

    Any feedback is more than welcome.
  2. robbieduncan Moderator emeritus


    Jul 24, 2002
    The Singleton design pattern is widely used and accepted. Look at NSUserDefaults for example...

    Apple even provide example code for this pattern in their Cocoa Fundamentals guide that all Cocoa/Cocoa Touch developers should have read...
  3. NickFalk thread starter macrumors 6502


    Jun 9, 2004
    Thanks Robbie.
    I have actually read that document, but then again I've probably read a few thousand pages of documentation, iPhone programming books, online tutorials, webcasts and forum threads since summer. It is only the last couple of weeks that I have actually had the time to sit down and do some coding.

    I find that some of the things I've read is completely gone, and to be frank there are lots of stuff that never stuck. I have a vague memory of the term singleton from another discussion somewhere but I guess I have to look it up in the mentioned document once more. Thanks.

Share This Page