1.该类在程序运行期间有且仅有一个实例
2.单例的优缺点
1)优点:单例可以保证系统中该类有且仅有一个实例,所以很便于外界访问.
因为其上面的特点,对于项目中的个别场景的传值,存储状态等等更加方便
2)缺点:单例实例一旦创建,对象指针是保存在静态区的,那么在堆区分配空间只有在应用程序终止后才会被释放
注:单例不能继承
3.单例的实现(所有的代码实现都是基于ARC模式下)
单例的实现重点就是防止在外部调用的时候出现多个不同的实例,并通过定义好的唯一方法返回唯一的实例
主要是做到以下几点:
防止调用 alloc]init]引起的错误
防止调用 new 引起的错误
防止调用 copy 引起的错误(应该不常用)
防止调用 mutableCopy 引起的错误(应该不常用)
1)重写以上4中方法,并在其中返回唯一实例
+ (instancetype)sharedSingleton {
static Singleton *_sharedSingleton = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
//不能再使用alloc方法
//因为已经重写了allocWithZone方法,所以这里要调用父类的分配空间的方法
_sharedSingleton = [[super allocWithZone:NULL] init];
});
return _sharedSingleton;
}
// 防止外部调用alloc 或者 new
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
return [Singleton sharedSingleton];
}
// 防止外部调用copy
- (id)copyWithZone:(nullable NSZone *)zone {
return [Singleton sharedSingleton];
}
// 防止外部调用mutableCopy
- (id)mutableCopyWithZone:(nullable NSZone *)zone {
return [Singleton sharedSingleton];
}
2)禁用以上4种方法,通过事先定义好的唯一方法返回实例
.h文件中加入如下代码禁用
- (instancetype)init NS_UNAVAILABLE;
+ (instancetype)new NS_UNAVAILABLE;
- (id)copy NS_UNAVAILABLE; // 没有遵循协议可以不写
- (id)mutableCopy NS_UNAVAILABLE; // 没有遵循协议可以不写
.m中实现自定义的调用方法
// 跟上面的方法实现有一点不同
+ (instancetype)sharedSingleton {
static Singleton *_sharedSingleton = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
// 要使用self来调用
_sharedSingleton = [[self alloc] init];
});
return _sharedSingleton;
}
注:一般单例都会通过share…方法来获取,虽然方法名可以随意写,但是最好使用share…来命名。