2

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.

evanwong
  • 5,054
  • 3
  • 31
  • 44
  • This is fast and guarantees you'll always get the same object no matter how you call it. Most people writing singletons are also the ones consuming them and so they (or their team) know not to try and allocate a new instance. – Jason Coco Jan 05 '12 at 18:36
  • If you want to make your class testable you can still `alloc`/`init` it. With Apple's singleton pattern you have to deal with the issue of setting up/tearing down the objects state between tests. – Paul.s Jan 05 '12 at 18:39
  • I think it is common to distribute some libraries/frameworks to other to use and those libraries/frameworks will use singleton. Yes, most developers should understand what sharedInstance mean and don't do any memory management to it by convention. However, you still have no way to really prevent it right? – evanwong Jan 05 '12 at 18:45

2 Answers2

2

Why not just combine the two?

Use the function you listed instead of Apple's + (MyGizmoClass*)sharedManager function, but implement all of the allocWithZone, copyWithZone, retain, retainCount, release, and autorelease overrides.

Lots more discussion here: What should my Objective-C singleton look like?

Community
  • 1
  • 1
MechEthan
  • 5,703
  • 1
  • 35
  • 30
0

If you want it to be a singleton, and you are worried about what happens if you call alloc/init: Don't do it! Simple as that.

There are cases, like NSFileManager, where you have both a singleton [NSFileManager defaultManager] but you can also have individual NSFileManager* objects. So this achieves it quite easily.

gnasher729
  • 51,477
  • 5
  • 75
  • 98