Game Development Reference
In-Depth Information
static dispatch_once_t once;
static MyManager* sharedManager;
dispatch_once(&once, ^{ sharedManager = [[self alloc] init]; });
return sharedManager;
Note Listing 3-2 is not only Apple's recommended way to write a singleton,
it's also the fastest and safest with only four lines of code. Yet singletons have a
long history, and you're bound to run into a number of solutions, most of which
basically do the exact same thing but with subtle differences. The Q&A site has a great discussion about Objective-C singletons in
which a great variety of implementations and their pros and cons are debated:
Singletons also have ugly sides. Because they're simple to use and implement and can
be accessed from any other class, there's a tendency to overuse them. They're like
global variables, which most programmers agree should be used scarcely and judi-
For example, you might think you have only one player object, so why not make the
player class a singleton? Everything seems to be fine—until you realize that whenever
the player advances from one level to another, the singleton not only keeps the player's
score but also his last animation frame, his health, and all the items he's picked up, and
then he might even begin the new level in Berserk mode because that mode was active
when he left the previous level.
To fix that, you add another method to reset certain variables when changing levels. So
far, so good. But as you add more features to the game, you end up having to add and
maintain more and more variables when switching a level. What's worse, suppose one
day a friend suggests you give the iPad version a two-player mode. But, wait, your
player is a singleton; you can have only one player at any time! This gives you a major
headache: refactor a lot of code or miss out on the cool two-player mode?
Or why not make the second player a singleton, too? And whenever the second player
needs to know something of the first player, it'll just use that singleton. So, they keep a
reference to each other, which means you can't have a single-player game without ini-
Search Nedrilad ::

Custom Search