Singleton with ARC


#1

A simple question I hope. I want to know how/if it is possible to create a singleton with ARC enabled?
When I try to create a singleton as listed on page 177 with ARC enabled I cannot create the three methods on the top of page 179: retain, release, and retain count. I understand that with ARC it is all or nothing, and since I have ARC enabled obviously I should not be able to override them. If I leave those three functions out of implementation file, will I still have a singleton?

Thanks.


#2

Yes you can. A better implementation of the Singleton pattern has been available since iOS 4 using GCD, (Grand Central Dispatch) and Blocks.

A good explanation can be found here: cocoasamurai.blogspot.com/2011/0 … wrong.html

TLDR: Note this is a great, simple and thread safe implementation.

[code]+(MyClass *)singleton
{
static dispatch_once_t pred;
static MyClass *shared = nil;

dispatch_once(&pred, ^{
shared = [[MyClass alloc] init];
});

return shared;
}[/code]

I actually came to visit the forum to ensure the 3rd edition uses this implementation. The problem for the authors is having to introduce GCD and Blocks. In the current edition Blocks are not covered until chapter 24, being an advanced but necessary topic. As far as I can tell they don’t cover Grand Central Dispatch at all, again another advanced topic.