-
-
Save MSch/943369 to your computer and use it in GitHub Desktop.
An implementation of a Singleton accesAn implementation of a Singleton accessor routine. Removes the (one if-statement) overhead of calling dispatch_once after the first time by method swizzling sharedInstance for a method without dispatch_once
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 <dispatch/dispatch.h> | |
#import <objc/runtime.h> | |
@implementation MySingleton | |
static MySingleton * __singleton = nil; | |
+ (MySingleton *) sharedInstance_accessor | |
{ | |
return ( __singleton ); | |
} | |
+ (MySingleton *) sharedInstance | |
{ | |
static dispatch_once_t __once = 0; | |
dispatch_once( &__once, ^{ | |
__singleton = [[self alloc] init]; | |
Method plainMethod = class_getInstanceMethod( self, @selector(sharedInstance) ); | |
Method accessorMethod = class_getInstanceMethod( self, @selector(sharedInstance_accessor) ); | |
method_exchangeImplementations( plainMethod, accessorMethod ); | |
}); | |
return ( __singleton ); | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Should it be class_getInstanceMethod or class_getClassMethod?