Skip to content

Instantly share code, notes, and snippets.

@elango
Forked from AlanQuatermain/SingletonInitializer.m
Created June 24, 2011 05:25
Show Gist options
  • Save elango/1044274 to your computer and use it in GitHub Desktop.
Save elango/1044274 to your computer and use it in GitHub Desktop.
An implementation of a Singleton accessor routine. Provides a dispatch_once-based version and a plain version for pre-(10.6|4.0) systems, with load-time method swapping to install the dispatch version if libdispatch is available at runtime.
#import <libkern/OSAtomic.h>
#import <dispatch/dispatch.h>
#import <objc/runtime.h>
@implementation MySingleton
+ (void) load
{
// check for weak-linked libdispatch symbols
if ( dispatch_queue_create != 0 )
{
Method plainMethod = class_getInstanceMethod( self, @selector(sharedInstance) );
Method dispatchMethod = class_getInstanceMethod( self, @selector(sharedInstance_dispatch_once) );
method_exchangeImplementations( plainMethod, dispatchMethod );
}
}
+ (MySingleton *) sharedInstance
{
static MySingleton * volatile __singleton = nil;
if ( __singleton == nil )
{
MySingleton * obj = [[self alloc] init];
if ( OSAtomicCompareAndSwapPtrBarrier(nil, obj, (void * volatile *)&__singleton) == false )
[obj release]; // already allocated/assigned by another thread
}
return ( __singleton );
}
+ (MySingleton *) sharedInstance_dispatch_once
{
// let libdispatch do the work for us
static MySingleton * volatile __singleton = nil;
static dispatch_once_t __once = 0;
dispatch_once( &__once, ^{ __singleton = [[self alloc] init]; });
return ( __singleton );
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment