Skip to content

Instantly share code, notes, and snippets.

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

This comment has been minimized.

Copy link

commented Nov 30, 2013

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