Skip to content

Instantly share code, notes, and snippets.

@lukeredpath
Created June 30, 2011 22:18
Show Gist options
  • Save lukeredpath/1057420 to your computer and use it in GitHub Desktop.
Save lukeredpath/1057420 to your computer and use it in GitHub Desktop.
Macro for creating your "shared instance" using GCD
@implementation MySharedThing
+ (id)sharedInstance
{
DEFINE_SHARED_INSTANCE_USING_BLOCK(^{
return [[self alloc] init];
});
}
@end
#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; \
@julei
Copy link

julei commented Oct 21, 2014

I am afraid that in this way it can't prevent creating multiple instances by 'alloc'.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment