First create a new header file that defines the following macros:
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 666768697071727374757677787980818283848586878889909192939495 |
// .h文件的实现
#define SingletonH(methodName) + (instancetype)shared##methodName;
// .m文件的实现
#if __has_feature(objc_arc) // 是ARC
#define SingletonM(methodName) \
static
id
_instace =
nil
; \
+ (
id
)allocWithZone:(
struct
_NSZone *)zone \
{ \
if
(_instace ==
nil
) { \
static
dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instace = [
super allocWithZone:zone]; \
}); \
} \
return
_instace; \
} \
\
- (
id
)init \
{ \
static
dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instace = [
super
init]; \
}); \
return
_instace; \
} \
\
+ (instancetype)shared##methodName \
{ \
return
[[
self
alloc] init]; \
} \
+ (
id
)copyWithZone:(
struct
_NSZone *)zone \
{ \
return
_instace; \
} \
\
+ (
id
)mutableCopyWithZone:(
struct
_NSZone *)zone \
{ \
return
_instace; \
}
#else // 不是ARC
#define SingletonM(methodName) \
static
id
_instace =
nil
; \
+ (
id
)allocWithZone:(
struct
_NSZone *)zone \
{ \
if
(_instace ==
nil
) { \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instace = [
super
allocWithZone:zone]; \
}); \
} \
return
_instace; \
} \
\
- (
id
)init \
{ \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instace = [
super
init]; \
}); \
return
_instace; \
} \
\
+ (instancetype)shared##methodName \
{ \
return
[[
self
alloc] init]; \
} \
\
- (oneway
void
)release \
{ \
\
} \
\
- (
id
)retain \
{ \
return
self
; \
} \
\
- (
NSUInteger
)retainCount \
{ \
return
1; \
} \
+ (
id
)copyWithZone:(
struct
_NSZone *)zone \
{ \
return
_instace; \
} \
\
+ (
id
)mutableCopyWithZone:(
struct
_NSZone *)zone \
{ \
return
_instace; \
}
#endif
|
And then in your definition of the Singleton class
. h file Write Singletonh (mymethodname)
. m file Write Singletonm (mymethodname)
Get!
Fast realization of OC single case