Created
August 16, 2013 14:03
-
-
Save macmade/6250215 to your computer and use it in GitHub Desktop.
Objective-C singleton macros
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
#ifdef OBJC_ARC | |
#define SingletonImplementation( name ) \ | |
\ | |
static name * __sharedInstance = nil; \ | |
\ | |
+ ( id )sharedInstance \ | |
{ \ | |
static dispatch_once_t token; \ | |
\ | |
dispatch_once \ | |
( \ | |
&token, \ | |
^ \ | |
{ \ | |
__sharedInstance = [ [ name alloc ] init ]; \ | |
} \ | |
); \ | |
\ | |
return __sharedInstance; \ | |
} \ | |
\ | |
- ( id )copy \ | |
{ \ | |
return __sharedInstance; \ | |
} \ | |
#else | |
#define SingletonImplementation( name ) \ | |
\ | |
static name * __sharedInstance = nil; \ | |
\ | |
@implementation name \ | |
\ | |
+ ( name * )sharedInstance \ | |
{ \ | |
@synchronized( self ) \ | |
{ \ | |
if( __sharedInstance == nil ) \ | |
{ \ | |
__sharedInstance = [ [ super allocWithZone: NULL ] init ]; \ | |
} \ | |
} \ | |
\ | |
return __sharedInstance; \ | |
} \ | |
\ | |
+ ( id )allocWithZone:( NSZone * )zone \ | |
{ \ | |
( void )zone; \ | |
\ | |
@synchronized( self ) \ | |
{ \ | |
if( [ self class ] != [ name class ] ) \ | |
{ \ | |
return [ super allocWithZone: zone ]; \ | |
} \ | |
\ | |
return [ [ self sharedInstance ] retain ]; \ | |
} \ | |
} \ | |
\ | |
- ( id )copyWithZone:( NSZone * )zone \ | |
{ \ | |
( void )zone; \ | |
\ | |
return self; \ | |
} \ | |
\ | |
- ( id )retain \ | |
{ \ | |
return self; \ | |
} \ | |
\ | |
- ( NSUInteger )retainCount \ | |
{ \ | |
return UINT_MAX; \ | |
} \ | |
\ | |
- ( oneway void )release \ | |
{} \ | |
\ | |
- ( id )autorelease \ | |
{ \ | |
return self; \ | |
} | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment