How do I implement an Objective-C singleton that is compatible with ARC? How do I implement an Objective-C singleton that is compatible with ARC? ios ios

How do I implement an Objective-C singleton that is compatible with ARC?


In exactly the same way that you (should) have been doing it already:

+ (instancetype)sharedInstance{    static MyClass *sharedInstance = nil;    static dispatch_once_t onceToken;    dispatch_once(&onceToken, ^{        sharedInstance = [[MyClass alloc] init];        // Do any other initialisation stuff here    });    return sharedInstance;}


if you want to create other instance as needed.do this:

+ (MyClass *)sharedInstance{    static MyClass *sharedInstance = nil;    static dispatch_once_t onceToken;    dispatch_once(&onceToken, ^{        sharedInstance = [[MyClass alloc] init];        // Do any other initialisation stuff here    });    return sharedInstance;}

else,you should do this:

+ (id)allocWithZone:(NSZone *)zone{    static MyClass *sharedInstance = nil;    static dispatch_once_t onceToken;    dispatch_once(&onceToken, ^{        sharedInstance = [super allocWithZone:zone];    });    return sharedInstance;}


This is a version for ARC and non-ARC

How To use:

MySingletonClass.h

@interface MySingletonClass : NSObject+(MySingletonClass *)sharedInstance;@end

MySingletonClass.m

#import "MySingletonClass.h"#import "SynthesizeSingleton.h"@implementation MySingletonClassSYNTHESIZE_SINGLETON_FOR_CLASS(MySingletonClass)@end