Method swizzling is used in the following singleton initializer but i am not sure about thread safety of swizzling.
What happens while a thread is about to call a method which is about to be swizzled by another method? Is it safe to swizzle in any time, while there are threads about to call that method? Answer with official references please. Thanks
#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