Skip to content

Instantly share code, notes, and snippets.

@MSch
Forked from AlanQuatermain/SingletonInitializer.m
Created April 26, 2011 22:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MSch/943369 to your computer and use it in GitHub Desktop.
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
#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
@lockedscope
Copy link

Should it be class_getInstanceMethod or class_getClassMethod?

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