OC中单例的实现方法
来源:互联网 发布:模拟退火算法的优缺点 编辑:程序博客网 时间:2024/06/05 09:51
1.使用GCD:
(1)在.h文件中提供一个类方法,用于返回该类唯一的一个对象
+ (Person *)sharePerson;(2)在.m文件中声明一个Static类型的对象,并将其置为nil,然后实现sharePerson和allocWithZone方法
// 静态全局变量static Person *person = nil;// 对外提供的获取单例的方法+ (Person *)sharePerson { if (!person) { person = [[self alloc] init]; } return person;}// 防止用户alloc+ (instancetype)allocWithZone:(struct _NSZone *)zone { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ person = [super allocWithZone:zone]; }); return person;}2.不使用GCD:
(1)在.h文件中提供一个类方法,用于返回该类唯一的一个对象
+ (Person *)sharePerson;(2)在.m文件中声明一个Static类型的对象,并将其置为nil,然后实现sharePerson和allocWithZone方法
// 静态全局变量static Person *person = nil;// 对外提供的获取单例的方法+ (Person *)sharePerson { <span style="color:#ff0000;">@synchronized</span>(self) { if (person == nil) { person = [[Person alloc] init]; } return person; }}// 防止用户alloc+ (instancetype)allocWithZone:(struct _NSZone *)zone { <span style="color:#ff0000;">@synchronized</span>(self) { if (person == nil) { person = [super allocWithZone:zone]; } return person; }}注:这两种方法都是线程安全的。
0 0
- OC中单例的实现方法
- OC 通讯录 实现的方法
- oc中类的具体实现方法
- oc中get set 方法的实现
- java内部类的OC实现方法
- OC语言 类方法的实现
- OC中实现单例的方法
- OC语法:实现拷贝的方法
- OC中setter方法与getter方法的内部实现
- OC 中一次性代码的两种实现方法
- OC 中一次性代码的两种实现方法
- OC没有实现方法警告
- OC运行和方法实现
- OC的构造方法
- oc方法的覆盖
- OC的description方法
- oc的私有方法
- oc中单例设计模式的实现
- webView
- C/C++中 static 用法总结
- 内存管理
- 常见字体清单
- struts2返回json数据的具体范例
- OC中单例的实现方法
- keil warning: #1-D: last line of file ends without a newline
- C语言的JSON 解析库 - MJSON使用介绍
- android sdk 安装出现warning:a folder failed to be moved
- 【BZOJ】【P2338】【HNOI2011】【数矩形】【题解】【乱搞】
- java常用包简介
- 数据结构上机测试1:顺序表的应用
- bzoj 2327: [HNOI2011]勾股定理
- 最大子数组的两种实现源码