博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
IOS中实现单例
阅读量:4597 次
发布时间:2019-06-09

本文共 664 字,大约阅读时间需要 2 分钟。

  在IOS中,所有对象的内存分配的方法都会调用allocWithZone,比如构造函数alloc,所以重写这个方法就可以实现单例。

  Xcode中预先写好了实现代码的快捷指令,敲dispatch_once就会看到。这个是有GCD实现的单例代码。

实现代码如下:

 

+(id)allocWithZone:(struct _NSZone *)zone{    static LYDemo * instance;    //是线程安全的,onceToKen默认是0    static dispatch_once_t onceToken;    //dispatch_once宏可以保证代码中的代码只会被执行一次。    dispatch_once(&onceToken, ^{        instance = [super allocWithZone:zone];    });    return instance;}//上面代码只是保证了这个类只能有一个实例,而易读性略差,我们应该模仿系统的单例方式。+(instancetype)sharedDemo{    return [[self alloc]init];}

 实现单例的步骤:

1.重写allocWithZone方法,使用GCD预先写好的代码块dispatch_once snippet。

2.创建一个以shared开头的方法,模仿系统的单例。

 

转载于:https://www.cnblogs.com/congliang/p/SingleInstance.html

你可能感兴趣的文章
poj 3764 The xor-longest Path (01 Trie)
查看>>
预备作业01
查看>>
【Spark】Spark-Redis连接池
查看>>
【云计算】使用supervisor管理Docker多进程-ntpd+uwsgi+nginx示例最佳实践
查看>>
Ubuntu16.04下配置ssh免密登录
查看>>
实验二 2
查看>>
will-change属性
查看>>
android学习笔记54——ContentProvider
查看>>
Unity3d android开发之触摸操作识别-双击,滑动去噪处理
查看>>
Custom view * is not using the 2- or 3-argument View constructors; XML attributes will not work
查看>>
模型选择准则
查看>>
安卓动态增加按钮
查看>>
iOS7程序后台运行
查看>>
maven+testng+reportng的pom设置
查看>>
IT telephone interview
查看>>
gitlab安装配置
查看>>
ps载入画笔
查看>>
悲怆:IT人的一声叹息->一个程序员的自白[转帖]
查看>>
[SpringMVC]自定义注解实现控制器访问次数限制
查看>>
日记(序)
查看>>