iOS-生成一个单例对象
2021-04-22 本文已影响0人
叫我龙哥
浅谈生成一个单例
单例作为非常常用的一个设计模式来说,是每个Coder必备的技能之一,但是还有很多人可能写了个假单例,就是我换种实例化方法可能就生成了一个新的对象。
1、为什么要生成一个单例对象
- 为了确保在整个应用期间只有一个实例,以达到用户的特定的使用目的。
- 对于频繁使用的对象,可以把多次创建对象所花费的时间节省下来,提高运行效率。
- 如果对象所占用的空间大,那么就可以节省大量不必要的空间,降了内存压力。
2、生成单例需要注意的问题
- 不同实例化方法可能返回不同的对象
3、如何生成一个单例
首先在当前类文件中声明一个全局静态对象
@implementation TestObjectClass
static TestObjectClass *_testClass = nil;
写一个类方法,初始化全局静态对象
+ (instancetype)shareObject{
if (_testClass == nil) {
_testClass = [[super alloc]init];
}
return _testClass;
}
重写allocWithZone方法,拦截alloc方法,防止生成新对象(使用synchronized,并优化同步锁)
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
if (_testClass == nil) {
@synchronized (self) {
if (_testClass == nil) {
_testClass = [super allocWithZone:zone];
}
}
}
return _testClass;
}
重写allocWithZone方法,拦截alloc方法,防止生成新对象(使用dispatch_once)
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
if (_testClass == nil) {
_testClass = [super allocWithZone:zone];
}
});
return _testClass;
}
重写copyWithZone方法,拦截copy方法,防止生成新对象
- (id)copyWithZone:(nullable NSZone *)zone {
return _testClass;
}
重写mutableCopyWithZone方法,拦截mutableCopy方法,防止生成新对象
- (id)mutableCopyWithZone:(nullable NSZone *)zone {
return _testClass;
}
如有纰漏请多多指教。
简书:https://www.jianshu.com/p/03eb4f2203bd
CSDN:https://blog.csdn.net/ZuoWeiXiaoDuZuoZuo/article/details/116001644