iOS Dev Nugget 17 Convenient macro to create a singleton class


Need to run a code review on your codebase? Hire me

Most projects need a singleton class or two. Even though it's mostly copy and paste, don't you wish they are easier to create?

Here's how:

@interface MyClass : NSObject

+ (MyClass*)sharedInstance;


@implementation MyClass

+ (MyClass*)sharedInstance {
        return [[self alloc] init];


The code above make use of the following macro:

  static dispatch_once_t pred = 0; \
  __strong static id _sharedObject = nil; \
  dispatch_once(&pred, ^{ \
    _sharedObject = block(); \
  }); \
  return _sharedObject;

The macro is courtesy of:

Your feedback is valuable: Do you want more nuggets like this?   Yes   or   No


Like this and want such iOS dev nuggets to be emailed to you, weekly?

Sign Me Up! or follow @iosdevnuggets on Twitter


View archives of past issues