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

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

1.    MRC中实现单例

创建单例设计模式的基本步骤

1> 声明一个单例对象的静态实例,并初始化为nil。

2> 创建一个类的类工厂方法,当且仅当这个类的实例为nil时生成一个该类的实例

3> 实现NScopying协议, 覆盖allocWithZone:方法,确保用户在直接分配和初始化对象时,不会产生另一个对象。

4> 覆盖release、autorelease、retain、retainCount方法, 以此确保单例的状态。

1>    在多线程的环境中,注意使用@synchronized关键字或GCD,确保静态实例被正确的创建和初始化。

2> // 单例的方法 解决资源抢夺问题

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

{

    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        _instance = [super allocWithZone:zone];

    });

 

    return _instance;

}

3>    单例创建的时候,提供shared或者类方法

以下为ARC和MRC中实现单例方法的宏定义

// 帮助实现单例设计模式

// .h文件的实现

#define SingletonH(methodName) + (instancetype)shared##methodName;

// .m文件的实现

#if __has_feature(objc_arc) // ARC

#define SingletonM(methodName) \

static id _instace = nil; \

+ (id)allocWithZone:(struct _NSZone *)zone \

{ \

if (_instace == nil) { \

static dispatch_once_t onceToken; \

dispatch_once(&onceToken, ^{ \

_instace = [super allocWithZone:zone]; \

}); \

} \

return _instace; \

} \

\

- (id)init \

{ \

static dispatch_once_t onceToken; \

dispatch_once(&onceToken, ^{ \

_instace = [super init]; \

}); \

return _instace; \

} \

\

+ (instancetype)shared##methodName \

{ \

return [[self alloc] init]; \

} \

+ (id)copyWithZone:(struct _NSZone *)zone \

{ \

return _instace; \

} \

\

+ (id)mutableCopyWithZone:(struct _NSZone *)zone \

{ \

return _instace; \

}

#else // 不是ARC

#define SingletonM(methodName) \

static id _instace = nil; \

+ (id)allocWithZone:(struct _NSZone *)zone \

{ \

if (_instace == nil) { \

static dispatch_once_t onceToken; \

dispatch_once(&onceToken, ^{ \

_instace = [super allocWithZone:zone]; \

}); \

} \

return _instace; \

} \

\

- (id)init \

{ \

static dispatch_once_t onceToken; \

dispatch_once(&onceToken, ^{ \

_instace = [super init]; \

}); \

return _instace; \

} \

\

+ (instancetype)shared##methodName \

{ \

return [[self alloc] init]; \

} \

\

- (oneway void)release \

{ \

\

} \

\

- (id)retain \

{ \

return self; \

} \

\

- (NSUInteger)retainCount \

{ \

return 1; \

} \

+ (id)copyWithZone:(struct _NSZone *)zone \

{ \

    return _instace; \

} \

 \

+ (id)mutableCopyWithZone:(struct _NSZone *)zone \

{ \

    return _instace; \

}

#endif

转载地址:http://qinpi.baihongyu.com/

你可能感兴趣的文章
pytorch(5)
查看>>
pytorch(6)
查看>>
ubuntu相关
查看>>
C++ 调用json
查看>>
nano中设置脚本开机自启动
查看>>
动态库调动态库
查看>>
Kubernetes集群搭建之CNI-Flanneld部署篇
查看>>
k8s web终端连接工具
查看>>
手绘VS码绘(一):静态图绘制(码绘使用P5.js)
查看>>
手绘VS码绘(二):动态图绘制(码绘使用Processing)
查看>>
基于P5.js的“绘画系统”
查看>>
《达芬奇的人生密码》观后感
查看>>
论文翻译:《一个包容性设计的具体例子:聋人导向可访问性》
查看>>
基于“分形”编写的交互应用
查看>>
《融入动画技术的交互应用》主题博文推荐
查看>>
链睿和家乐福合作推出下一代零售业隐私保护技术
查看>>
Unifrax宣布新建SiFAB™生产线
查看>>
艾默生纪念谷轮™在空调和制冷领域的百年创新成就
查看>>
NEXO代币持有者获得20,428,359.89美元股息
查看>>
Piper Sandler为EverArc收购Perimeter Solutions提供咨询服务
查看>>