Singletons in Objective-C with ARC

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:

Leave a Reply

Your email address will not be published. Required fields are marked *