在开发中经常会用到单例设计模式,目的就是为了在程序的整个生命周期内,只会创建一个类的实例对象,而且只要程序不被杀死,该实例对象就不会被释放。常用的2中创建单例的方法:利用GCD方式;互斥锁方式创建。
1.利用GCD方式创建单例
#import "ClassA.h"
@implementation ClassA
static ClassA *classA = nil;//静态的该类的实例
+ (instancetype)sharedClassA
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
classA = [[self alloc] init];
});
return classA;
}
+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
classA = [super allocWithZone:zone];
});
return classA;
}
- (id)copyWithZone:(NSZone *)zone
{
return classA;
}
- (id)mutableCopyWithZone:(NSZone *)zone {
return classA;
}
@end
2.互斥锁方式
+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
@synchronized(self) {
if (classA == nil) {
classA = [super allocWithZone:zone];
}
}
return classA;
}
+ (instancetype)sharedInstance
{
@synchronized(self) {
if (classA == nil) {
classA = [[self alloc] init];
}
}
return classA;
}
- (id)copyWithZone:(NSZone *)zone
{
return classA;
}
***还有就是当一个项目工程中需要用到多个单例时,可以利用宏来把单例提出来,可以节省类的创建:
在Singleton.h文件中:
#define SingletonH(name) + (instancetype)shared##name;
#define SingletonM(name) \
static id _instance; \
\
+ (instancetype)allocWithZone:(struct _NSZone *)zone \
{ \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instance = [super allocWithZone:zone]; \
}); \
return _instance; \
} \
\
+ (instancetype)shared##name \
{ \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instance = [[self alloc] init]; \
}); \
return _instance; \
} \
\
- (id)copyWithZone:(NSZone *)zone \
{ \
return _instance; \
}\
\
- (id)mutableCopyWithZone:(NSZone *)zone { \
return _instance; \
}