Created
November 2, 2010 14:45
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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
Could you let me have the ARC version of this?