ios单例模式的实现
来源:互联网 发布:闪字制作软件下载 编辑:程序博客网 时间:2024/06/15 00:45
有两种方法实现单例
创建一个singleTool单例类
方法一使用同步锁功能代码如下
在在.h文件中
+(singleTool*)shareTool;
在.m文件中实现
+(singleTool*)shareTool
{
Static singleTool*tool=nil;
@synchronized(self){
if(self==nil){
tool=[singleTool alloc]init];
}
}
return tool;
}
+(id)allocWithZone:(NSZone*)zone
{
@synchronized(self){
if(!tool){
tool=[super initWithZone:zone];
return tool
}
return nil;
}
}
-(id)copyWithZone:(zone)
{
return tool;
}
使用synchronized同步锁保证不同线程执行这个方法时只有第一个线程执行完后,其他线程才执行对应方法,但是第一个线程已经创建了tool对象tool!=nil所以剩下的线程的操作不会再创建新的实例对象了从而保证单列类只实例一个对象,同步锁会影响性能。所以苹果推荐使用方法二:
使用GCD来
在.m文件中实现
+(singleTool*)shareTool
{
Static singleTool *tool=nil;
Static dispatch_once_t token;
dispatch_once(&token,^{
if(tool==nil){
tool=[singleTool alloc]init];
}
})
return tool;
}-(id)copyWithZone:(zone)
{
Static dispatch_once_t token;
dispatch_once(&token,^{
if(tool==nil){
tool=[super initWithZone:zone];
}
})
return tool;
}
dispatch_once保证程序在运行中只会执行一次从而保证只会创建一个实例对象
- iOS单例模式的实现
- iOS singleton单例模式的实现
- iOS单例模式的实现
- iOS单例模式的实现
- iOS单例模式的实现
- iOS单例模式的实现
- iOS单例模式的实现
- iOS单例模式的实现
- iOS单例模式的实现
- iOS单例模式的实现
- iOS单例模式的实现
- ios单例模式的实现
- ios单例模式的实现
- iOS中的单例模式的实现
- iOS 单例模式的实现
- ios单例模式的实现
- iOS单例模式实现
- iOS 单例模式实现
- BZOJ 1145 [CTSC 2008] 树状数组+组合数学
- Codeforces Round #424 C Jury Marks 思维
- InnoDB调优-索引优化策略
- hrbust 1401 九连环(矩阵快速幂)
- c++ Premier 学习笔记(unit2 变量和基本类型 -声明与定义
- ios单例模式的实现
- 解决weex点击事件触发两次
- hibernate_多对多关联关系配置
- 安卓高德地图定位篇-(1)
- Mockito与Spring中@Autowired与@InjectMocks组合
- 有向图—朱刘算法模板
- 牛客网《剑指Offer》 矩形覆盖
- NYOJ 90 整数划分
- Regularization