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

cescofry picture cescofry · Sep 27, 2011 · Viewed 92k times · Source

How do I convert (or create) a singleton class that compiles and behaves correctly when using automatic reference counting (ARC) in Xcode 4.2?

Answer

Nick Forge picture Nick Forge · Sep 27, 2011

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;
}