单例模式
2016-01-10 00:00
197 查看
单例模式-ARC
1.在.m中保留一个全局的static的实例static id _instance;
2.重写allocWithZone:方法,在这里创建唯一的实例(注意线程安全)
+ (id)allocWithZone:(struct _NSZone *)zone { @synchronized(self) { if (!_instance) { _instance = [super allocWithZone:zone]; } } return _instance; }
3.提供1个类方法让外界访问唯一的实例
+ (instancetype)sharedSoundTool { @synchronized(self) { if (!_instance) { _instance = [[self alloc] init]; } } return _instance; }
4.实现copyWithZone:方法
+ (id)copyWithZone:(struct _NSZone *)zone { return _instance; }
单例模式 – MRC
非ARC中(MRC),单例模式的实现(比ARC多了几个步骤)实现内存管理方法
- (id)retain { return self; } - (NSUInteger)retainCount { return 1; } - (oneway void)release {} - (id)autorelease { return self; }
相关文章推荐
- iOS多线程之NSOperation
- OC选择排序和冒泡排序
- 【嘉兴东臣php】PHP基础学习周总结
- 【嘉兴东臣php】ajax
- C++简单的文件读写操作
- Effective C++: 数字类型与类型提升.
- Algorithm: 插入排序
- 操作NSString
- ABP 屏蔽 hao123
- 屏蔽各种没用的
- 事务隔离级别新看法!
- UWP之坑-MediaElement全屏
- 第一章 Spring概述
- nodejs小项目之用户管理
- PHP程序员应该知道的15个库
- 用PHP编写一个APP的API
- 【RBAC】打造Web权限控制系统
- 一个印度人写的文章,看完惊出一身冷汗,肯定包括你!
- iOS开发工具-网络封包分析工具Charles
- 【微信技能】如何通过微信号知道对方微信的二维码