Create singletons in Objective-C

Here's how to create singletones in Objective-C:

First the interface, declare a class method as such...

@interface AppAPI : NSObject

+(AppAPI *)instance;

@end

Then implement it accordingly...

@implementation AppAPI

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

// instance singleton
+(AppAPI *)instance {
    static AppAPI *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc]init];
    });
    return instance;
}

@end

Important Note: One additional note about this pattern is that it will not work if the instance method is first accessed in a different thread than the main thread.

If you are at all concerned with ensuring your instance works inside multi-threaded code you can use the following pattern... which I highly recommend:

+(AppAPI *) instance {
   static AppAPI *theInstance = nil;
   static dispatch_once_t onceToken;
   if([NSThread isMainThread]) {
      dispatch_once(&onceToken, ^{
         theInstance = [[self alloc]init];
      });
   } else {
      dispatch_sync(dispatch_get_main_queue(), ^{
        dispatch_once(&onceToken, ^{
          theInstance = [[self alloc]init];
        });
      });
   }
}

This code will check to see if you are on the main thread. If you are, it will create the instance on main thread. If not, it enqueues the dispatch_once on the main thread using queue using dispatch_sync.

comments powered by Disqus