Created
June 30, 2011 22:18
-
Star
(117)
You must be signed in to star a gist -
Fork
(21)
You must be signed in to fork a gist
-
-
Save lukeredpath/1057420 to your computer and use it in GitHub Desktop.
Macro for creating your "shared instance" using GCD
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@implementation MySharedThing | |
+ (id)sharedInstance | |
{ | |
DEFINE_SHARED_INSTANCE_USING_BLOCK(^{ | |
return [[self alloc] init]; | |
}); | |
} | |
@end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; \ |
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
Thank you for sharing such a great technique! Here is a slightly modified version:
It allows two forms of shared object initialization: one-line
and multi-line (notice curly braces around the block of code):
It can be used in the right part of an assignment as well:
This modification utilizes two language features: GCC compound expressions extension, which is also supported by Clang, and C99 variadic macros support.