read

The singleton pattern is widely used in iOS to have a global, static class.

The most famous is [NSUserDefaults standardUserDefaults].

Over the years, the template for creating a singleton/SharedInstance has also changed. This is due to the introduction of new technologies in Apple’s SDK, particularly ARC and GDC.

The implementation has simplified to:

+ (id)sharedInstance
{
  static dispatch_once_t pred = 0;
  __strong static id _sharedObject = nil;
  dispatch_once(&pred, ^{
    _sharedObject = [[self alloc] init]; // or some other init method
  });
  return _sharedObject;
}

Nice piece of code added to my Xcode snippet.


Image

@samwize

¯\_(ツ)_/¯

Back to Home