Danny's Lab

Engineering the World

Singletons in Objective-C with ARC

Published on: Sep 6, 2012
Reading time: 19 seconds

Automatic Reference Counting (ARC) simplifies a lot in Objective-C, including singletons. Here's a template for you:

+ (id)sharedInstance { static dispatch_once_t pred = 0;      __strong static id _sharedObject = nil;      dispatch_once(&pred, ^{           _sharedObject = [[self alloc] init]; // Additional initialization can go here      });      return _sharedObject; }

Source: