// Singleton.h
// 帮助实现单例设计模式,代码同时兼容ARC和非ARC工程;定义两个宏,在其他工具类直接调用宏,就可以实现单例模式
// alloc方法内部会调用allocWithZone:
// .h文件的实现
#define SingletonH(methodName) + (instancetype)share##methodName;
// .m文件的实现
#if __has_feature(objc_arc) // 是ARC
#define SingletonM (methodName) \
static id _instance = nil; \
+ (id)allocWithZone:(struct _NSZone *)zone { \
if (_instance == nil) { \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instance = [super allocWithZone:zone]; \
}); \
} \
return _instance; \
} \
\
- (id)init { \
static dispatch_once_t onceToken; \
dispatch_once( &onceToken, ^{ \
_instance = [super init]; \
}); \
return _instance; \
} \
\
+ (id)copyWithZone:(struct _NSZone *)zone { \
return _instance; \
} \
\
+ (id)mutableCopyWithZone:(struct _NSZone *)zone { \
return _instance; \
} \
\
+ (instancetype)share##methodName { \
return [[self alloc] init]; \
}
#else // 不是ARC
#define SingletonM (methodName) \
static id _instance = nil; \
+ (id)allocWithZone:(struct _NSZone *)zone { \
if (_instance == nil) { \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instance = [super allocWithZone:zone]; \
}); \
} \
return _instance; \
} \
\
- (id)init { \
static dispatch_once_t onceToken; \
dispatch_once( &onceToken, ^{ \
_instance = [super init]; \
}); \
return _instance; \
} \
\
+ (id)copyWithZone:(struct _NSZone *)zone { \
return _instance; \
} \
\
+ (id)mutableCopyWithZone:(struct _NSZone *)zone { \
return _instance; \
} \
\
+ (instancetype)share##methodName { \
return [[self alloc] init]; \
} \
\
- (oneway void)release { \
\
} \
\
- (id)retain { \
return self; \
} \
\
- (NSInteger)retainCount { \
return 1; \
}
// 注意最后一行不要加\,加\的意思是该行的下一行是宏定义的部分
// LYSoundTool.h
#import <Foundation/Foundation.h>
#import “Singleton.h”
@interface LYSoundTool : NSObject
SingletonH(SoundTool) // 在.h文件里面使用SingletonH宏定义
@end
// LYSoundTool.m
#import “LYSoundTool.h”
@interface LYSoundTool()
@end
@implementation LYSoundTool
SingletonM(SoundTool) // 在.m文件里面使用SingletonM宏定义
@end
// LYHttpTool.h
#import <Foundation/Foundation.h>
#import “Singleton.h”
@interface LYHttpTool : NSObject <NSCoping>
SingletonH(HttpTool)
@end
// LYHttpTool.m
#import “LYHttpTool.h”
@implementation LYHttpTool
SingletonM(HttpTool)
@end
</pre>