Clicky

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;

@end

@implementation MyClass

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

@end

The code above make use of the following macro:

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

The macro is courtesy of: https://gist.github.com/1057420


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