iOS 单例的写法
来源:互联网 发布:不亦远乎是什么意思 编辑:程序博客网 时间:2024/05/09 16:50
关于什么是单例,iOS中的单例模式是什么,自行爬页搜索。这里抛砖引玉,说说单例模式应该怎样实现。
直接上代码。
//// Singleton.h// SingletonDemo//// Created by WangBo on 3/9/16.// Copyright © 2016 WangBo. All rights reserved.//#import <Foundation/Foundation.h>@interface Singleton : NSObject+ (instancetype)shareInstance;@end
//// Singleton.m// SingletonDemo//// Created by WangBo on 3/9/16.// Copyright © 2016 WangBo. All rights reserved.//#import "Singleton.h"@implementation Singletonstatic Singleton *_singleton = nil;+ (instancetype)shareInstance { static dispatch_once_t predicate; dispatch_once(&predicate, ^{ _singleton = [[super allocWithZone:NULL] init];//调用super的allocWithZone方法,是因为self的该方法在下面被重载了 }); return _singleton;}+ (id)allocWithZone:(struct _NSZone *)zone { return [self shareInstance];}+ (id)copyWithZone:(struct _NSZone *)zone { return [self shareInstance];}@end
//// main.m// SingletonDemo//// Created by WangBo on 3/9/16.// Copyright © 2016 WangBo. All rights reserved.//#import "Singleton.h"#import <Foundation/Foundation.h>int main(int argc, const char *argv[]) { @autoreleasepool { // insert code here... Singleton *singleton1 = [Singleton shareInstance]; NSLog(@"%@", singleton1); Singleton *singleton2 = [Singleton shareInstance]; NSLog(@"%@", singleton2); Singleton *singleton3 = [Singleton shareInstance]; NSLog(@"%@", singleton3); } return 0;}
程序输出:
2016-03-09 19:27:31.375 SingletonDemo[11477:206113] <Singleton: 0x100302340>2016-03-09 19:27:31.376 SingletonDemo[11477:206113] <Singleton: 0x100302340>2016-03-09 19:27:31.376 SingletonDemo[11477:206113] <Singleton: 0x100302340>Program ended with exit code: 0
我们可以看到,三个对象对应内存中同一个值。
说明:
1.之所以要重载allocWithZone、copyWithZone方法,是因为如果不这样做,客户端通过这两个方法会得到一个新的实例,违背了我们单例模式的思想;
2.本文使用dispatch_once函数实现单例Singleton的初始化,因此只会在程序运行周期中执行一次,保重了单例的单一性。同时满足了线程安全的要求。
3.考虑到线程安全,我们同样可以使用对self加锁的方式来实现,@synchronized、NSLock,自行爬文搜索。
收工!~
1 0
- ios 单例的写法
- iOS 单例的写法
- ios 单例的写法
- iOS 单例写法
- ios 单例写法
- ios单例写法
- iOS单例写法
- iOS 单例写法
- ios 单例模式的写法
- iOS 标准单例的写法
- ios 单例模式的写法
- iOS 单例的标准写法
- iOS单例的完整写法
- ios 单例的几种写法
- iOS单例的最终写法
- IOS 单例模式的写法
- iOS 开发 单例的写法
- iOS单例模式的官方写法
- 排序二叉树转为双向列表
- 安卓基础:http处理XML文件
- 动态代理模式
- Html学习笔记(6)-与浏览者交互,表单标签
- 指针相关知识点
- iOS 单例的写法
- ORA-12537: TNS:connection closed
- Html学习笔记(5)-Html标签(4)
- 基于动画原理的提高
- Linux环境下,在不停止程序的情况下,更换动态链接库
- Html学习笔记(4)-Html标签(3)
- Checkbutton 和 Radiobutton
- HDU2795线段树之单点更新
- 55-题目1104:整除问题