332
votes

My singleton accessor method is usually some variant of:

static MyClass *gInstance = NULL;

+ (MyClass *)instance
{
    @synchronized(self)
    {
        if (gInstance == NULL)
            gInstance = [[self alloc] init];
    }

    return(gInstance);
}

What could I be doing to improve this?

2
  • 27
    What you have is fine, though you could move the global variable declaration into your +instance method (the only place it needs to be used, unless you're allowing it to be set as well) and use a name like +defaultMyClass or +sharedMyClass for your method. +instance isn't intention-revealing. Commented Sep 28, 2008 at 9:37
  • Since it's unlikely the 'answer' to this question will change any time soon, I'm placing a historical lock on the question. Two reasons 1) Lots of views, votes, and good content 2) To prevent yo-yoing of open/closed. It was a great question for its time, but questions of these types are not appropriate for Stack Overflow. We now have Code Review for checking working code. Please take all discussion of this question to this meta question. Commented Mar 21, 2013 at 19:52

26 Answers 26

207
votes

Another option is to use the +(void)initialize method. From the documentation:

The runtime sends initialize to each class in a program exactly one time just before the class, or any class that inherits from it, is sent its first message from within the program. (Thus the method may never be invoked if the class is not used.) The runtime sends the initialize message to classes in a thread-safe manner. Superclasses receive this message before their subclasses.

So you could do something akin to this:

static MySingleton *sharedSingleton;

+ (void)initialize
{
    static BOOL initialized = NO;
    if(!initialized)
    {
        initialized = YES;
        sharedSingleton = [[MySingleton alloc] init];
    }
}
15
  • 7
    If the runtime will only ever call this once, what does the BOOL do? Is that a precaution in case someone calls this function explicitly from their code? Commented Apr 3, 2009 at 17:28
  • 5
    Yes, it is a precaution since the function can also be called directly. Commented Apr 8, 2009 at 4:32
  • 33
    This also is required because there could be subclasses. If they don’t override +initialize their superclasses implementation will be called if the subclass is first used.
    – anon
    Commented Sep 6, 2010 at 21:25
  • 3
    @Paul you can override the release method and make it empty. :)
    – user142019
    Commented Mar 25, 2011 at 22:20
  • 4
    @aryaxt: From the docs listed, this is already thread safe. So, the call is once per runtime -- period. This would seem to be the correct, thread-safe, optimally efficient solution.
    – lilbyrdie
    Commented Jun 23, 2011 at 13:52
95
votes
@interface MySingleton : NSObject
{
}

+ (MySingleton *)sharedSingleton;
@end

@implementation MySingleton

+ (MySingleton *)sharedSingleton
{
  static MySingleton *sharedSingleton;

  @synchronized(self)
  {
    if (!sharedSingleton)
      sharedSingleton = [[MySingleton alloc] init];

    return sharedSingleton;
  }
}

@end

[Source]

9
  • 7
    This is all you should usually use for singletons. Among other things, keeping your classes separately instantiable makes them easier to test, because you can test separate instances instead of having a way to reset their state. Commented Sep 28, 2008 at 9:36
  • 3
    Stig Brautaset: No, it is not okay to leave out the @synchronized in this example. It is there to handle the possible race-condition of two threads executing this static function at the same time, both getting past the "if(!sharedSingleton)" test at the same time, and thus resulting in two [MySingleton alloc]s... The @synchronized {scope block} forces that hypothetical second thread to wait for the first thread to exit the {scope block} before being allowed to proceed into it. I hope this helps! =)
    – MechEthan
    Commented Jul 13, 2011 at 16:29
  • 3
    What stops someone from still making their own instance of the object? MySingleton *s = [[MySingelton alloc] init];
    – lindon fox
    Commented Oct 28, 2011 at 5:31
  • 1
    @lindonfox What is the answer to your question?
    – khatchad
    Commented Dec 20, 2011 at 21:48
  • 1
    @Raffi - sorry I think I must have forgot to paste in my answer. Anyway, I got the book Pro Objective-C Design Patterns for iOS and it spells out how you make a "strict" singelton. Basically since you can't make the initiating methods private, you need to override the methods alloc and copy. So if you try and do something like [[MySingelton alloc] init] you will get a run time error (though not a compile time error unfortunately). I don't understand how all the details of the object creation, but you implement + (id) allocWithZone:(NSZone *)zone which is called in sharedSingleton
    – lindon fox
    Commented Dec 21, 2011 at 3:42
59
votes

Per my other answer below, I think you should be doing:

+ (id)sharedFoo
{
    static dispatch_once_t once;
    static MyFoo *sharedFoo;
    dispatch_once(&once, ^ { sharedFoo = [[self alloc] init]; });
    return sharedFoo;
}
5
  • 6
    Don't bother with all of what you're doing above. Make your (hopefully extremely few) singletons separately-instantiable, and just have a shared/default method. What you've done is only necessary if you really, truly, ONLY want a single instance of your class. Which you don't, esp. for unit tests. Commented Sep 28, 2008 at 9:35
  • The thing is this is the Apple sample code for "creating a singleton". But yeah, you're absolutely right. Commented Oct 23, 2008 at 1:39
  • 1
    The Apple sample code is correct if you want a "true" singleton (i.e. an object that can only be instantiated once, ever) but as Chris says, this is rarely what you want or need whereas some kind of settable shared instance is what you usually want. Commented Jul 25, 2009 at 1:25
  • Here is a macro for the above method: gist.github.com/1057420. This is what I use.
    – Kobski
    Commented Jan 30, 2012 at 19:21
  • 1
    Unit tests aside, there's nothing speaking against this solution, correct? And it's fast and safe.
    – CodeSmile
    Commented Apr 6, 2012 at 20:19
58
votes

Since Kendall posted a threadsafe singleton that attempts to avoid locking costs, I thought I would toss one up as well:

#import <libkern/OSAtomic.h>

static void * volatile sharedInstance = nil;                                                

+ (className *) sharedInstance {                                                                    
  while (!sharedInstance) {                                                                          
    className *temp = [[self alloc] init];                                                                 
    if(!OSAtomicCompareAndSwapPtrBarrier(0x0, temp, &sharedInstance)) {
      [temp release];                                                                                   
    }                                                                                                    
  }                                                                                                        
  return sharedInstance;                                                                        
}

Okay, let me explain how this works:

  1. Fast case: In normal execution sharedInstance has already been set, so the while loop is never executed and the function returns after simply testing for the variable's existence;

  2. Slow case: If sharedInstance doesn't exist, then an instance is allocated and copied into it using a Compare And Swap ('CAS');

  3. Contended case: If two threads both attempt to call sharedInstance at the same time AND sharedInstance doesn't exist at the same time then they will both initialize new instances of the singleton and attempt to CAS it into position. Whichever one wins the CAS returns immediately, whichever one loses releases the instance it just allocated and returns the (now set) sharedInstance. The single OSAtomicCompareAndSwapPtrBarrier acts as both a write barrier for the setting thread and a read barrier from the testing thread.

6
  • 18
    This is complete overkill for the at-most one time it can happen during an application's lifetime. Nevertheless, it is spot-on correct, and the compare-and-swap technique is a useful tool to know about, so +1. Commented Apr 22, 2010 at 14:37
  • Nice answer - the OSAtomic family is a good thing to know about
    – Bill
    Commented Feb 27, 2011 at 1:24
  • 1
    @Louis: Amazing, really enlightening answer! One question though: what should my init method do in your approach? Throwing an exception when sharedInstance is initialized is not a good idea, I believe. What to do then to prevent user calling init directly many times?
    – matm
    Commented Sep 1, 2011 at 16:39
  • 2
    I generally don't prevent it. There are often valid reasons to allow what is generally a singleton to multiply instantiated, the most commons is for certain types of unit testing. If I really wanted to enforce a single instance I would probably have the init method check to see if the global existed, and if it did I have it release self and return the global. Commented Sep 2, 2011 at 3:57
  • 1
    @Tony bit late of response, but OSAtomicCompareAndSwapPtrBarrier requires a volatile. Perhaps the volatile keyword is to keep the compiler from optimizing away the check? See: stackoverflow.com/a/5334727/449161 and developer.apple.com/library/mac/#documentation/Darwin/Reference/…
    – Ben Flynn
    Commented Nov 16, 2012 at 18:23
14
votes
static MyClass *sharedInst = nil;

+ (id)sharedInstance
{
    @synchronize( self ) {
        if ( sharedInst == nil ) {
            /* sharedInst set up in init */
            [[self alloc] init];
        }
    }
    return sharedInst;
}

- (id)init
{
    if ( sharedInst != nil ) {
        [NSException raise:NSInternalInconsistencyException
            format:@"[%@ %@] cannot be called; use +[%@ %@] instead"],
            NSStringFromClass([self class]), NSStringFromSelector(_cmd), 
            NSStringFromClass([self class]),
            NSStringFromSelector(@selector(sharedInstance)"];
    } else if ( self = [super init] ) {
        sharedInst = self;
        /* Whatever class specific here */
    }
    return sharedInst;
}

/* These probably do nothing in
   a GC app.  Keeps singleton
   as an actual singleton in a
   non CG app
*/
- (NSUInteger)retainCount
{
    return NSUIntegerMax;
}

- (oneway void)release
{
}

- (id)retain
{
    return sharedInst;
}

- (id)autorelease
{
    return sharedInst;
}
2
  • 3
    I noticed that clang complains about a leak if you don't assign the result of [[self alloc] init] to sharedInst.
    – pix0r
    Commented May 6, 2009 at 18:21
  • Subverting init like this is a pretty ugly approach IMO. Don't mess with init and/or the actual creation of the object. If you instead go for a controlled point of access to a shared instance, while not hard-baking singleton into the object, you'll have a happier time later if writing tests etc. Hard singletons are far too overused.
    – occulus
    Commented Jan 14, 2013 at 13:41
12
votes

Edit: This implementation obsoleted with ARC. Please have a look at How do I implement an Objective-C singleton that is compatible with ARC? for correct implementation.

All the implementations of initialize I've read in other answers share a common error.

+ (void) initialize {
  _instance = [[MySingletonClass alloc] init] // <----- Wrong!
}

+ (void) initialize {
  if (self == [MySingletonClass class]){ // <----- Correct!
      _instance = [[MySingletonClass alloc] init] 
  }
}

The Apple documentation recommend you check the class type in your initialize block. Because subclasses call the initialize by default. There exists a non-obvious case where subclasses may be created indirectly through KVO. For if you add the following line in another class:

[[MySingletonClass getInstance] addObserver:self forKeyPath:@"foo" options:0 context:nil]

Objective-C will implicitly create a subclass of MySingletonClass resulting in a second triggering of +initialize.

You may think that you should implicitly check for duplicate initialization in your init block as such:

- (id) init { <----- Wrong!
   if (_instance != nil) {
      // Some hack
   }
   else {
      // Do stuff
   }
  return self;
}

But you will shoot yourself in the foot; or worse give another developer the opportunity to shoot themselves in the foot.

- (id) init { <----- Correct!
   NSAssert(_instance == nil, @"Duplication initialization of singleton");
   self = [super init];
   if (self){
      // Do stuff
   }
   return self;
}

TL;DR, here's my implementation

@implementation MySingletonClass
static MySingletonClass * _instance;
+ (void) initialize {
   if (self == [MySingletonClass class]){
      _instance = [[MySingletonClass alloc] init];
   }
}

- (id) init {
   ZAssert (_instance == nil, @"Duplication initialization of singleton");
   self = [super init];
   if (self) {
      // Initialization
   }
   return self;
}

+ (id) getInstance {
   return _instance;
}
@end

(Replace ZAssert with our own assertion macro; or just NSAssert.)

1
  • 1
    I would just live simpler and avoid initialize altogether. Commented May 17, 2012 at 13:24
10
votes

A thorough explanation of the Singleton macro code is on the blog Cocoa With Love

http://cocoawithlove.com/2008/11/singletons-appdelegates-and-top-level.html.

9
votes

I have an interesting variation on sharedInstance that is thread safe, but does not lock after the initialization. I am not yet sure enough of it to modify the top answer as requested, but I present it for further discussion:

// Volatile to make sure we are not foiled by CPU caches
static volatile ALBackendRequestManager *sharedInstance;

// There's no need to call this directly, as method swizzling in sharedInstance
// means this will get called after the singleton is initialized.
+ (MySingleton *)simpleSharedInstance
{
    return (MySingleton *)sharedInstance;
}

+ (MySingleton*)sharedInstance
{
    @synchronized(self)
    {
        if (sharedInstance == nil)
        {
            sharedInstance = [[MySingleton alloc] init];
            // Replace expensive thread-safe method 
            // with the simpler one that just returns the allocated instance.
            SEL origSel = @selector(sharedInstance);
            SEL newSel = @selector(simpleSharedInstance);
            Method origMethod = class_getClassMethod(self, origSel);
            Method newMethod = class_getClassMethod(self, newSel);
            method_exchangeImplementations(origMethod, newMethod);
        }
    }
    return (MySingleton *)sharedInstance;
}
8
  • 1
    +1 that's really intriguing. I might use class_replaceMethod to transform sharedInstance into a clone of simpleSharedInstance. That way you wouldn't ever have to worry about acquiring an @synchronized lock again. Commented Feb 19, 2010 at 6:19
  • It's the same effect, using exchangeImplementations means that after init when you call sharedInstance, you are really calling simpleSharedInstance. I actually started out with replaceMethod, but decided it was better to just switch the implementations around so the original still existed if needed... Commented Feb 19, 2010 at 7:46
  • In further testing, I could not get replaceMethod to work - in repeated calls, the code still called the original sharedInstance instead of simpleSharedInstance. I think it may be because they are both class level methods... The replace I used was: class_replaceMethod(self, origSel, method_getImplementation(newMethod), method_getTypeEncoding(newMethod)); and some variations thereof. I can verify the code I have posted works and simpleSharedInstance is called after the first pass through sharedInstance. Commented Feb 19, 2010 at 7:58
  • You can make a thread safe version that does not pay locking costs after initialization without doing a bunch of runtime mucking, I have posted an implementation below. Commented Mar 15, 2010 at 18:57
  • 1
    +1 great idea. I just love those things one can do with the runtime. But in most cases this probably is premature optimization. If I’d really have to get rid of the synchronization cost I’d probably use the lockless version by Louis.
    – anon
    Commented Sep 6, 2010 at 21:35
6
votes

Short answer: Fabulous.

Long answer: Something like....

static SomeSingleton *instance = NULL;

@implementation SomeSingleton

+ (id) instance {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (instance == NULL){
            instance = [[super allocWithZone:NULL] init];
        }
    });
    return instance;
}

+ (id) allocWithZone:(NSZone *)paramZone {
    return [[self instance] retain];
}

- (id) copyWithZone:(NSZone *)paramZone {
    return self;
}

- (id) autorelease {
    return self;
}

- (NSUInteger) retainCount {
    return NSUIntegerMax;
}

- (id) retain {
    return self;
}

@end

Be sure to read the dispatch/once.h header to understand what's going on. In this case the header comments are more applicable than the docs or man page.

0
5
votes

I've rolled singleton into a class, so other classes can inherit singleton properties.

Singleton.h :

static id sharedInstance = nil;

#define DEFINE_SHARED_INSTANCE + (id) sharedInstance {  return [self sharedInstance:&sharedInstance]; } \
                               + (id) allocWithZone:(NSZone *)zone { return [self allocWithZone:zone forInstance:&sharedInstance]; }

@interface Singleton : NSObject {

}

+ (id) sharedInstance;
+ (id) sharedInstance:(id*)inst;

+ (id) allocWithZone:(NSZone *)zone forInstance:(id*)inst;

@end

Singleton.m :

#import "Singleton.h"


@implementation Singleton


+ (id) sharedInstance { 
    return [self sharedInstance:&sharedInstance];
}

+ (id) sharedInstance:(id*)inst {
    @synchronized(self)
    {
        if (*inst == nil)
            *inst = [[self alloc] init];
    }
    return *inst;
}

+ (id) allocWithZone:(NSZone *)zone forInstance:(id*)inst {
    @synchronized(self) {
        if (*inst == nil) {
            *inst = [super allocWithZone:zone];
            return *inst;  // assignment and return on first allocation
        }
    }
    return nil; // on subsequent allocation attempts return nil
}

- (id)copyWithZone:(NSZone *)zone {
    return self;
}

- (id)retain {
    return self;
}

- (unsigned)retainCount {
    return UINT_MAX;  // denotes an object that cannot be released
}

- (void)release {
    //do nothing
}

- (id)autorelease {
    return self;
}


@end

And here is an example of some class, that you want to become singleton.

#import "Singleton.h"

@interface SomeClass : Singleton {

}

@end

@implementation SomeClass 

DEFINE_SHARED_INSTANCE;

@end

The only limitation about Singleton class, is that it is NSObject subclass. But most time I use singletons in my code they are in fact NSObject subclasses, so this class really ease my life and make code cleaner.

1
2
votes

This works in a non-garbage collected environment also.

@interface MySingleton : NSObject {
}

+(MySingleton *)sharedManager;

@end


@implementation MySingleton

static MySingleton *sharedMySingleton = nil;

+(MySingleton*)sharedManager {
    @synchronized(self) {
        if (sharedMySingleton == nil) {
            [[self alloc] init]; // assignment not done here
        }
    }
    return sharedMySingleton;
}


+(id)allocWithZone:(NSZone *)zone {
    @synchronized(self) {
        if (sharedMySingleton == nil) {
            sharedMySingleton = [super allocWithZone:zone];
            return sharedMySingleton;  // assignment and return on first allocation
        }
    }
    return nil; //on subsequent allocation attempts return nil
}


-(void)dealloc {
    [super dealloc];
}

-(id)copyWithZone:(NSZone *)zone {
    return self;
}


-(id)retain {
    return self;
}


-(unsigned)retainCount {
    return UINT_MAX;  //denotes an object that cannot be release
}


-(void)release {
    //do nothing    
}


-(id)autorelease {
    return self;    
}


-(id)init {
    self = [super init];
    sharedMySingleton = self;

    //initialize here

    return self;
}

@end
2
votes

Shouln't this be threadsafe and avoid the expensive locking after the first call?

+ (MySingleton*)sharedInstance
{
    if (sharedInstance == nil) {
        @synchronized(self) {
            if (sharedInstance == nil) {
                sharedInstance = [[MySingleton alloc] init];
            }
        }
    }
    return (MySingleton *)sharedInstance;
}
1
2
votes

Here's a macro that I put together:

http://github.com/cjhanson/Objective-C-Optimized-Singleton

It is based on the work here by Matt Gallagher But changing the implementation to use method swizzling as described here by Dave MacLachlan of Google.

I welcome comments / contributions.

1
  • the link seems broken - where can I get that source?
    – amok
    Commented Aug 29, 2010 at 21:09
2
votes

How about

static MyClass *gInstance = NULL;

+ (MyClass *)instance
{
    if (gInstance == NULL) {
        @synchronized(self)
        {
            if (gInstance == NULL)
                gInstance = [[self alloc] init];
        }
    }

    return(gInstance);
}

So you avoid the synchronization cost after initialization?

1
  • See discussions of Dual Checked Locking in other answers.
    – i_am_jorf
    Commented Mar 6, 2013 at 21:34
2
votes

For an in-depth discussion of the singleton pattern in Objective-C, look here:

Using the Singleton Pattern in Objective-C

1
vote

KLSingleton is:

  1. Subclassible (to the n-th degree)
  2. ARC compatible
  3. Safe with alloc and init
  4. Loaded lazily
  5. Thread-safe
  6. Lock-free (uses +initialize, not @synchronize)
  7. Macro-free
  8. Swizzle-free
  9. Simple

KLSingleton

5
  • 1
    I'm using your NSSingleton for my project, and It seems to be incompatible with KVO. The matter is that KVO creates subclass for every KVO object with prefixing it NSKVONotifying_MyClass. And it makes MyClass +initialize and -init methods to be called twice. Commented Jul 3, 2012 at 18:28
  • I tested this on the latest Xcode and didn't have any trouble registering for or receiving KVO events. You can verify this with the following code: gist.github.com/3065038 As I mentioned on Twitter, the +initialize methods are called once for NSSingleton and once for each subclass. This is a property of Objective-C. Commented Jul 7, 2012 at 6:19
  • If you add NSLog(@"initialize: %@", NSStringFromClass([self class])); to the +initialize method you can verify that the classes are initialized only once. Commented Jul 7, 2012 at 6:24
  • NSLog(@"initialize: %@", NSStringFromClass([self class])); Commented Jul 7, 2012 at 10:24
  • You might want to also have it be IB compatible. Mine is: stackoverflow.com/questions/4609609/… Commented Sep 5, 2012 at 19:55
0
votes

You don't want to synchronize on self... Since the self object doesn't exist yet! You end up locking on a temporary id value. You want to ensure that no one else can run class methods ( sharedInstance, alloc, allocWithZone:, etc ), so you need to synchronize on the class object instead:

@implementation MYSingleton

static MYSingleton * sharedInstance = nil;

+( id )sharedInstance {
    @synchronized( [ MYSingleton class ] ) {
        if( sharedInstance == nil )
            sharedInstance = [ [ MYSingleton alloc ] init ];
    }

    return sharedInstance;
}

+( id )allocWithZone:( NSZone * )zone {
    @synchronized( [ MYSingleton class ] ) {
        if( sharedInstance == nil )
            sharedInstance = [ super allocWithZone:zone ];
    }

    return sharedInstance;
}

-( id )init {
    @synchronized( [ MYSingleton class ] ) {
        self = [ super init ];
        if( self != nil ) {
            // Insert initialization code here
        }

        return self;
    }
}

@end
3
  • 1
    The rest of the methods, accessor methods, mutator methods, etc should synchronize on self. All class(+) methods and initializers (and probably -dealloc) should synchronize on the class object. You can avoid having to manually sync if you use Objective-C 2.0 properties instead of accessor/mutator methods. All object.property and object.property = foo, are automatically synchronized to self.
    – Rob Dotson
    Commented Jan 13, 2010 at 22:10
  • 3
    Please explain why you think that the self object doesn't exist in a class method. The runtime determines which method implementation to invoke based on the exact same value that it provides as self to every method (class or instance).
    – dreamlax
    Commented Feb 19, 2010 at 6:53
  • 2
    Inside of a class method, self is the class object. Try it yourself: #import <Foundation/Foundation.h> @interface Eggbert : NSObject + (BOOL) selfIsClassObject; @end @implementation Eggbert + (BOOL) selfIsClassObject { return self == [Eggbert class]; } @end int main (int argc, const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; NSLog(@"%@", [Eggbert selfIsClassObject] ? @"YES" : @"NO"); [pool drain]; return 0; }
    – jscs
    Commented Sep 27, 2011 at 2:23
0
votes

Just wanted to leave this here so I don't lose it. The advantage to this one is that it's usable in InterfaceBuilder, which is a HUGE advantage. This is taken from another question that I asked:

static Server *instance;

+ (Server *)instance { return instance; }

+ (id)hiddenAlloc
{
    return [super alloc];
}

+ (id)alloc
{
    return [[self instance] retain];
}


+ (void)initialize
{
    static BOOL initialized = NO;
    if(!initialized)
    {
        initialized = YES;
        instance = [[Server hiddenAlloc] init];
    }
}

- (id) init
{
    if (instance)
        return self;
    self = [super init];
    if (self != nil) {
        // whatever
    }
    return self;
}
0
votes
static mySingleton *obj=nil;

@implementation mySingleton

-(id) init {
    if(obj != nil){     
        [self release];
        return obj;
    } else if(self = [super init]) {
        obj = self;
    }   
    return obj;
}

+(mySingleton*) getSharedInstance {
    @synchronized(self){
        if(obj == nil) {
            obj = [[mySingleton alloc] init];
        }
    }
    return obj;
}

- (id)retain {
    return self;
}

- (id)copy {
    return self;
}

- (unsigned)retainCount {
    return UINT_MAX;  // denotes an object that cannot be released
}

- (void)release {
    if(obj != self){
        [super release];
    }
    //do nothing
}

- (id)autorelease {
    return self;
}

-(void) dealloc {
    [super dealloc];
}
@end
0
votes

I know there are a lot of comments on this "question", but I don't see many people suggesting using a macro to define the singleton. It's such a common pattern and a macro greatly simplifies the singleton.

Here are the macros I wrote based on several Objc implementations I've seen.

Singeton.h

/**
 @abstract  Helps define the interface of a singleton.
 @param  TYPE  The type of this singleton.
 @param  NAME  The name of the singleton accessor.  Must match the name used in the implementation.
 @discussion
 Typcially the NAME is something like 'sharedThing' where 'Thing' is the prefix-removed type name of the class.
 */
#define SingletonInterface(TYPE, NAME) \
+ (TYPE *)NAME;


/**
 @abstract  Helps define the implementation of a singleton.
 @param  TYPE  The type of this singleton.
 @param  NAME  The name of the singleton accessor.  Must match the name used in the interface.
 @discussion
 Typcially the NAME is something like 'sharedThing' where 'Thing' is the prefix-removed type name of the class.
 */
#define SingletonImplementation(TYPE, NAME) \
static TYPE *__ ## NAME; \
\
\
+ (void)initialize \
{ \
    static BOOL initialized = NO; \
    if(!initialized) \
    { \
        initialized = YES; \
        __ ## NAME = [[TYPE alloc] init]; \
    } \
} \
\
\
+ (TYPE *)NAME \
{ \
    return __ ## NAME; \
}

Example of use:

MyManager.h

@interface MyManager

SingletonInterface(MyManager, sharedManager);

// ...

@end

MyManager.m

@implementation MyManager

- (id)init
{
    self = [super init];
    if (self) {
        // Initialization code here.
    }

    return self;
}

SingletonImplementation(MyManager, sharedManager);

// ...

@end

Why a interface macro when it's nearly empty? Code consistency between the header and code files; maintainability in case you want to add more automatic methods or change it around.

I'm using the initialize method to create the singleton as is used in the most popular answer here (at time of writing).

0
votes

With Objective C class methods, we can just avoid using the singleton pattern the usual way, from:

[[Librarian sharedInstance] openLibrary]

to:

[Librarian openLibrary]

by wrapping the class inside another class that just has Class Methods, that way there is no chance of accidentally creating duplicate instances, as we're not creating any instance!

I wrote a more detailed blog here :)

1
  • Your link no longer functions.
    – i_am_jorf
    Commented Mar 6, 2013 at 21:14
0
votes

To extend the example from @robbie-hanson ...

static MySingleton* sharedSingleton = nil;

+ (void)initialize {
    static BOOL initialized = NO;
    if (!initialized) {
        initialized = YES;
        sharedSingleton = [[self alloc] init];
    }
}

- (id)init {
    self = [super init];
    if (self) {
        // Member initialization here.
    }
    return self;
}
0
votes

My way is simple like this:

static id instanceOfXXX = nil;

+ (id) sharedXXX
{
    static volatile BOOL initialized = NO;

    if (!initialized)
    {
        @synchronized([XXX class])
        {
            if (!initialized)
            {
                instanceOfXXX = [[XXX alloc] init];
                initialized = YES;
            }
        }
    }

    return instanceOfXXX;
}

If the singleton is initialized already, the LOCK block will not be entered. The second check if(!initialized) is to make sure it is not initialized yet when the current thread acquires the LOCK.

1
0
votes

I've not read through all the solutions, so forgive if this code is redundant.

This is the most thread safe implementation in my opinion.

+(SingletonObject *) sharedManager
{
    static SingletonObject * sharedResourcesObj = nil;

    @synchronized(self)
    {
        if (!sharedResourcesObj)
        {
            sharedResourcesObj = [[SingletonObject alloc] init];
        }
    }

    return sharedResourcesObj;
}
-4
votes

I usually use code roughly similar to that in Ben Hoffstein's answer (which I also got out of Wikipedia). I use it for the reasons stated by Chris Hanson in his comment.

However, sometimes I have a need to place a singleton into a NIB, and in that case I use the following:

@implementation Singleton

static Singleton *singleton = nil;

- (id)init {
    static BOOL initialized = NO;
    if (!initialized) {
        self = [super init];
        singleton = self;
        initialized = YES;
    }
    return self;
}

+ (id)allocWithZone:(NSZone*)zone {
    @synchronized (self) {
        if (!singleton)
            singleton = [super allocWithZone:zone];     
    }
    return singleton;
}

+ (Singleton*)sharedSingleton {
    if (!singleton)
        [[Singleton alloc] init];
    return singleton;
}

@end

I leave the implementation of -retain (etc.) to the reader, although the above code is all you need in a garbage collected environment.

1
  • 2
    Your code is not thread-safe. It uses synchronized in the alloc method, but not in the init method. Checking on the initialized bool is not thread-safe.
    – Mecki
    Commented Jun 29, 2009 at 12:44
-5
votes

The accepted answer, although it compiles, is incorrect.

+ (MySingleton*)sharedInstance
{
    @synchronized(self)  <-------- self does not exist at class scope
    {
        if (sharedInstance == nil)
            sharedInstance = [[MySingleton alloc] init];
    }
    return sharedInstance;
}

Per Apple documentation:

... You can take a similar approach to synchronize the class methods of the associated class, using the Class object instead of self.

Even if using self works, it shouldn't and this looks like a copy and paste mistake to me. The correct implementation for a class factory method would be:

+ (MySingleton*)getInstance
{
    @synchronized([MySingleton class]) 
    {
        if (sharedInstance == nil)
            sharedInstance = [[MySingleton alloc] init];
    }
    return sharedInstance;
}
4
  • 6
    self most certainly does exist it class scope. It refers to the class instead of the instance of the class. Classes are (mostly) first class objects.
    – schwa
    Commented Jan 25, 2011 at 18:30
  • Why do you put @synchroninzed WITHIN a method?
    – user4951
    Commented May 4, 2011 at 2:06
  • 1
    As schwa already said, self is the class object inside of a class method. See my comment for a snippet demonstrating this.
    – jscs
    Commented Sep 27, 2011 at 2:27
  • self exists, but using it as the identifier passed to @synchronized will synchronize access to the methods of the instance. As @user490696 points out, there are cases (like singletons) where using the class object is preferable. From The Obj-C Programming Guide: You can take a similar approach to synchronize the class methods of the associated class, using the class object instead of self. In the latter case, of course, only one thread at a time is allowed to execute a class method because there is only one class object that is shared by all callers.
    – quellish
    Commented Feb 8, 2012 at 19:50

Not the answer you're looking for? Browse other questions tagged or ask your own question.