PDA

View Full Version : Creating a global instance of an Object?




NickFalk
Mar 5, 2009, 05:39 AM
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.



robbieduncan
Mar 5, 2009, 05:44 AM
The Singleton design pattern is widely used and accepted. Look at NSUserDefaults for example...

Apple even provide example code (http://developer.apple.com/documentation/Cocoa/Conceptual/CocoaFundamentals/CocoaObjects/chapter_3_section_10.html#//apple_ref/doc/uid/TP40002974-CH4-SW32) for this pattern in their Cocoa Fundamentals guide that all Cocoa/Cocoa Touch developers should have read...

NickFalk
Mar 5, 2009, 05:52 AM
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.