There are different ways to create a singleton/shared instance of a class in Objective-C.
Here I have explained two most preferred methods for it and both are thread safe.
1) Using "@synthesize"
#define SINGLETON_FOR_CLASS(yourclassname) \
\
static yourclassname *shared##yourclassname = nil; \
\
+ (yourclassname *)shared##yourclassname \
{ \
@synchronized(self) \
{ \
if (shared##yourclassname == nil) \
{ \
shared##yourclassname = [[self alloc] init]; \
} \
} \
\
return shared##yourclassname; \
} \
\
2 ) Using "dispatch_once" from GCD
#define SINGLETON_FOR_CLASS(yourclassname)\
+ (id) shared##yourclassname {\
static dispatch_once_t pred = 0;\
__strong static id _sharedObject = nil;\
dispatch_once(&pred, ^{\
_sharedObject = [[self alloc] init];\
});\
return _sharedObject;\
}
Both the methods above are thread safe. There is only one difference between these two, dispatch_once is much faster than @synthesize.
I have created these methods as a macro. To use any of the method import the macro file in your class for which you need to create a shared instance.
Put following line in the header file of your class.
+(id)sharedyourclassname;
And in implementation class add following to create a singleton.
SINGLETON_FOR_CLASS(yourclassname);
Whatever class name you pass here it will create a singleton for that class.
0 Comment(s)