Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

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
You can’t perform that action at this time.