博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
iOS单例模式
阅读量:6895 次
发布时间:2019-06-27

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

单例模式是iOS开发中的一种很常用的开发模式,他的特点是让某一个类只有一个实例,在项目全局访问他的时候,他只有一个实例就保证了数据的唯一性。通常用于全局都需要使用的一个实例变量。

下面以定位功能为例,代码实现功能

1.先创建一个类

GXLocation

 

2.然后声明一个静态实例变量

static GXLocation *gxlocation;

 

3.用GCD的一次方法创建一个类的实例

 

+(instancetype) shareGXlocation

{

    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        gxlocation = [[self alloc] init];

    });

    return gxlocation;

}

 

3.重写allocWithZone方法

+(instancetype)allocWithZone:(struct _NSZone *)zone

{

    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        if (gxlocation == nil) {

            gxlocation = [super allocWithZone:zone];

        }

    });

    return gxlocation;

}

 

-(id)copyWithZone:(NSZone *)zone

{

    return gxlocation;

}

 

-(id)mutableCopyWithZone:(NSZone *)zone

{

    return gxlocation;

}

 

创建完成之后,调用的时候就直接调用shareGXlocation方法,就会获取唯一实例

 

转载于:https://www.cnblogs.com/yxl-151217/p/10830524.html

你可能感兴趣的文章
PIE SDK创建掩膜
查看>>
(四)springmvc+mybatis+dubbo+zookeeper分布式架构 整合 - maven代码结构
查看>>
SQL查询到的数据放到DataSet中
查看>>
mybatis的selectOne和selectList没有数据返回时的问题
查看>>
批处理+组策略 实现规定时间段无法开机and定时关机
查看>>
我的升级
查看>>
centos 6.4 server 安装nginx
查看>>
JS OOP -04 JS中的公有成员,私有成员和静态成员
查看>>
Elevator
查看>>
nx-admin 引入Ueditor
查看>>
npm包的安装与卸载命令行总结
查看>>
glide 镜像
查看>>
struts2
查看>>
Ensemble Learning 之 Gradient Boosting 与 GBDT
查看>>
Nginx启动报错
查看>>
后台进程管理supervisor
查看>>
Laravel请求/Cookies/文件上传
查看>>
解决toast一直吐司的方法
查看>>
NFC简介
查看>>
计算bubble有多少个求大神教教
查看>>