单例是一种设计模式,顾名思义就是创建只有一个实例变量的对象; 创建方法如下
创建一个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
- (void)viewDidLoad {
[super viewDidLoad];
//获取单例SInstance 调用单例方法
NSInteger num = [[SingleInstance shareInstance]getNumber];
NSLog(@"%ld",num);
}
//结果如图