Skip to content

Instantly share code, notes, and snippets.

@xjones
Forked from lukeredpath/ExampleClass.m
Created October 21, 2011 21:59
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xjones/1305095 to your computer and use it in GitHub Desktop.
Save xjones/1305095 to your computer and use it in GitHub Desktop.
Macro for creating your "shared instance" using GCD
@implementation MySharedThing
// Using method 1
//
DEFINE_SHARED_INSTANCE_FOR_CLASS(MySharedThing)
// Using method 2
//
+ (id)sharedInstance
{
DEFINE_SHARED_INSTANCE_USING_BLOCK(^{
return [[self alloc] init];
});
}
@end
//
// GCDSingleton.h
//
// Macros to simplify creating of a sharedInstance for a class using GCD (ARC compliant)
//
// Use one of the following methods to create a sharedInstance
//
//
// METHOD #1: use this if you want the sharedInstance method to be 'sharedClassName'
//
// @implementation MySharedThing
//
// DEFINE_SHARED_INSTANCE_FOR_CLASS(MySharedThing)
//
#define DEFINE_SHARED_INSTANCE_FOR_CLASS(className) \
+ (id)shared##className \
{ \
static dispatch_once_t pred = 0; \
__strong static id _sharedObject = nil; \
dispatch_once(&pred, ^{ \
_sharedObject = ^{return [[self alloc] init];}(); \
}); \
return _sharedObject; \
} \
//
// METHOD #2: use this if you want to name the 'sharedXXX' method yourself
//
// @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; \
@xjones
Copy link
Author

xjones commented Oct 21, 2011

Thanks to @lukeredpath for the original.

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