MRC环境-单例实现
.h文件实现
@interface DemoSoundTool : NSObject
+ (instancetype)sharedSoundTool;
.m文件实现
实现一个类方法
重写五个系统方法
#import "DemoSoundTool.h"
@implementation DemoSoundTool
static DemoSoundTool *_soundTool = nil;
/**
* alloc方法内部会调用allocWithZone:
* zone : 系统分配给app的内存
*/
+ (id)allocWithZone:(struct _NSZone *)zone
{
if (_soundTool == nil) {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{ // 安全(这个代码只会被调用一次)
_soundTool = [super allocWithZone:zone];
});
}
return _soundTool;
}
- (id)init
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_soundTool = [super init];
});
return _soundTool;
}
+ (instancetype)sharedSoundTool
{
return [[self alloc] init];
}
- (oneway void)release
{
}
- (id)retain
{
return self;
}
- (NSUInteger)retainCount
{
return 1;
}
ARC环境下- 单例实现
不重写 release, retain, retainCount这三个函数即可, 其他 和 MRC一样
当需要定义多个 单例的时候, 每个单例内部实现基本一样, 这时可以[ 抽取一个宏 ] 实现单例, 减少代码量开支
定义一个头文件singleton.h
// 帮助实现单例设计模式
// .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
宏定义之后,就可以一句话搞定 单例
例如在MRC环境下 , 单例模式可以这样实现
.h文件实现
#import "Singleton.h"
@interface DemoSoundTool : NSObject
SingletonH(SoundTool)
.m文件实现
#import "Singleton.h"
#import "DemoSoundTool.h"
@implementation DemoSoundTool
//这样一句话就搞定了
SingletonM(SoundTool)
@end