#undef As_singleton
#define As_singleton (__class) \
-(__class *) sharedinstance; \
+ (__class *) sharedinstance;
#undef Def_singleton
#define Def_singleton (__class) \
-(__class *) sharedinstance \
{ \
return [__class sharedinstance]; \
} \
+ (__class *) sharedinstance \
{ \
Static dispatch_once_t once; \
Static __class * __SINGLETON__; \
Dispatch_once (&once, ^{__singleton__ = [[[Self class] alloc] init];}); \
return __singleton__; \
} \
+ (Instancetype) Allocwithzone: (struct _nszone *) zone \
{ \
Static dispatch_once_t once; \
Static __class * __SINGLETON__; \
Dispatch_once (&once, ^{__singleton__ = [Super Allocwithzone:zone];}); \
return __singleton__; \
}
How to use: Declare As_singleton (__class) in. h
. M declaration Def_singleton (__class)
Explanation: In order to prevent others from accidentally using the Alloc/init way to create the example, but also to prevent others deliberately, we have to ensure that no matter how the creation can only be the same instance object, this will have to rewrite Allocwithzone; I didn't have this before, this is Alloc init. and shareinstance created not the same
Reference Link: Http://www.cocoachina.com/ios/20160713/17017.html?ref=myread This is written in detail.
iOS OC Single macro definition