单例、单例模式
来源:互联网 发布:惠阳区网络问政 编辑:程序博客网 时间:2024/04/28 10:18
简单的实现一个单例:
- +
(instancetype)sharedInstance { -
static MyClass *_instance = nil; -
static dispatch_once_t predicate; -
dispatch_once(&predicate, ^{ -
_instance = [[MyClass alloc] init]; -
}); -
return _instance; - }
真正的单例模式:
+ (MyClass *)sharedInstance { // 第二步:实例构造检查静态实例是否为nil
staticMyClass *_instance = nil;
static
@synchronized (self) {
if (!_instance) {
_instance = [[super allocWithZone:NULL] init];
}
}
return _instance;
}
+ (id)allocWithZone:(NSZone *)zone { // 第三步:重写allocWithZone方法
}
+ (id)allocWithZone:(NSZone *)zone { // 第三步:重写allocWithZone方法
if (!_instance) {
_instance= [[MyClass alloc] init];
return_instance;
}
return nil;
}
- (id)copyWithZone:(NSZone *)zone{ // 第四步
return self;
}
// 以下只在MRC下才需要写,因为在ARC下不让调用一下方法,所以不用担心引用计数的问题。
- (id)retain {
return self;
}
- (NSUInteger)retainCount {
return NSUIntegerMAX;
}
- (void)release {
}
- (id)autorelease {
return self;
}
}
- (id)copyWithZone:(NSZone *)zone{ // 第四步
return self;
}
// 以下只在MRC下才需要写,因为在ARC下不让调用一下方法,所以不用担心引用计数的问题。
- (id)retain {
return self;
}
- (NSUInteger)retainCount {
return NSUIntegerMAX;
}
- (void)release {
}
- (id)autorelease {
return self;
}
0 1
- 单例、单例模式
- 单例模式-多线程单例模式
- 单件模式(单例模式)
- 单例(Singleton)模式
- 深入浅出单例模式
- 浅谈单例模式
- 单例模式
- 单例模式
- 单例模式陷阱
- 单例模式
- 单例模式实现
- singleton 单例模式
- 单例模式
- 单例模式
- Singleteton单例模式
- java单例模式
- 单例模式1
- Python单例模式
- MYSQL性能查看(命中率,慢查询)
- 剑指offer面试题之跳台阶
- AppBar的简单使用
- 计算一个整数的二进制中有多少个1
- 函数指针做函数参数
- 单例、单例模式
- 百练2798:2进制转化为16进制
- 1000 Tables Moving
- Ajax的使用步骤
- 中文分词之Java实现使用IK Analyzer实现
- 1014. Waiting in Line (30)
- Xcode免证书打包ipa
- awk使用
- 无线性能优化