I am new in Objective-C and I am trying to create a singleton class based on Apple\'s documentation.
+ (MyGizmoClass*)sharedManager
{
if (sharedGizmoManager
There is a couple of things to consider here. First, the Cocoa Fundamentals guide is somewhat out-of date. It doesn't take into account some of the current technologies Apple has developed, like Grand Central Dispatch, and Automated Reference Counting. The [retain] in your allocWithZone method would not compile correctly in a ARC-enabled project (since you're new to Obj-C, I'm making an assumption here you're new to iOS/iPhone as well, and so you should read up on those two technologies).
There is a very good discussion of different singleton design patterns over in this thread: What should my Objective-C singleton look like?
However that is an older thread, and as such does not take into account Automated Reference Counting (I've utilized Louis Gerbang's answer for years and it no longer works in ARC-enabled projects).
For ARC-enabled projects/files (yes ARC can be enabled just for single files) - we've moved to a singleton that uses GCD and works quite well:
static YourClassName * volatile sharedInstance = nil;
+ (YourClassName *)sharedInstance
{
static dispatch_once_t sharedInstanceToken;
dispatch_once(&sharedInstanceToken, ^{
sharedInstance = [[YourClassName alloc] init];
});
return sharedInstance;
}
What's going on here? Well if you take a look through the GCD docs, you'll see dispatch_once only gets executed once during the entire lifetime of an application for a particular object. As the docs go onto say, this makes it very useful for creating singletons in a thread-safe manner.
On top of that, we declare the sharedInstance method as volatile, meaning the compiler/runtime should never try to cache a call to the method and should always execute the code inside. This makes sure we always call into GCD and that we always get back the object we're supposed to.
I'm glossing over a bunch since you're new to Obj-C, but definetly take a look into GCD, ARC, and then once you've got a solid grounding in Obj-C, looking into IMP caching, which is what volatile is preventing from happening.