Skip to content

Instantly share code, notes, and snippets.

@AlanQuatermain
Created November 2, 2010 14:45
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save AlanQuatermain/659709 to your computer and use it in GitHub Desktop.
Save AlanQuatermain/659709 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
@nishimu
Copy link

nishimu commented Jul 27, 2012

Could you let me have the ARC version of this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment