I have seen many people suggesting to use dispatch_once to do the singleton:
+(MyClass *)singleton {
static dispatch_once_t pred;
static MyClass *shared = nil;
dispatch_once(&pred, ^{
shared = [[MyClass alloc] init];
});
return shared;
}
Why is this better when it doesn’t really support true singleton, and people can still use init to create an instance and even do a release on the sharedInstance?
Apple’s way is preventing all those cases
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CocoaFundamentals/CocoaObjects/CocoaObjects.html
I know it is not thread-safe, but I think it is easy to put a synchronize block there to make it thread-safe.
Why not just combine the two?
Use the function you listed instead of Apple’s
+ (MyGizmoClass*)sharedManagerfunction, but implement all of theallocWithZone,copyWithZone,retain,retainCount,release, andautoreleaseoverrides.Lots more discussion here: What should my Objective-C singleton look like?