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
.