单例模式定义与使用
2016-03-19 17:26
302 查看
单例是一种设计模式,顾名思义就是创建只有一个实例变量的对象; 创建方法如下
创建一个SingleInstance继承自NSObject
@interface SingleInstance :
NSObject
1.在.h文件里面定义一个调用函数 和需要单例调用的方法
//定义一个使用单例变量的调用方法
+(SingleInstance *)shareInstance;
//定义一个获得数字的使用函数
-(NSInteger)getNumber;
@end
2.在.m里面
// 创建一个静态区对象
static SingleInstance *sInstance =
nil;
@implementation SingleInstance
//单例的调用方法 每一次调用返回的都是sInstance这一个实例变量
+(SingleInstance *)shareInstance
{
//判断对象是否为空
if(sInstance ==
nil)
{ //空,创建一个
sInstance = [[SingleInstance
alloc]init];
}
//不空,
返回单例
return
sInstance;
}
//单例变量的方法
-(NSInteger)getNumber
{
//随机0-9的数
NSInteger num =
arc4random() % 10;
NSLog(@"%ld",num);
//返回数
return num;
}
3.在ViewController里面使用
//导入头文件
#import"SingleInstance.h"
@interface
ViewController ()
@end
@implementation ViewController
9578
- (void)viewDidLoad {
[super
viewDidLoad];
//获取单例SInstance
调用单例方法
NSInteger num = [[SingleInstance
shareInstance]getNumber];
NSLog(@"%ld",num);
}
//结果如图
相关文章推荐
- HDU1711 Number Sequence【机智 or KMP模板】
- quickbuild 设置使用外部数据库
- 由主线程更新UI所想到的Window和RootViewImpl的创建过程
- 项目中遇到的问题(一)弹出UIAlertController 时出现 Warning: Attempt to present * on * which is already presenting
- Description Resource Path Location Type The project was not built since its
- 【网页设计】行业文字规范你知道吗?太原UI设计师讲
- 哈理工 OJ 1950--QuickPow(快速幂)
- @RequestParam和@PathVariable用法小结
- UIViewControllerAnimatedTransitioning UIViewControllerTransitionCoordinator 回顾
- UI-基本控件的简单使用
- 解决创建XIB 与UIView关联
- 编写第一个 Arduino 程序
- 用PriorityQueue解决选择最小的K个数问题
- RequireJs运行原理
- django matching query does not exist.
- Arduino Uno 硬件电路
- 用js验证字符串是否匹配guid类型20160319
- LeetCode 303. Range Sum Query - Immutable
- UITabbarController
- 让你明白response.sendRedirect()与request.getRequestDispatcher().forward()区别