Skip to content

Instantly share code, notes, and snippets.

@vinnybad
Created February 13, 2015 06:13
Show Gist options
  • Save vinnybad/c67dfc27f8a860fccd1a to your computer and use it in GitHub Desktop.
Save vinnybad/c67dfc27f8a860fccd1a to your computer and use it in GitHub Desktop.
Thread-safe Singletons in Modern Objective-C (The Short Way)
// the block that's passed in needs to return an object
#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;
#import "EVCCommon.h"
@implementation EVCSomeClass
+(instancetype)shared {
DEFINE_SHARED_INSTANCE_USING_BLOCK(^{
return [EVCSomeClass new];
});
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment