单例
来源:互联网 发布:北京用友软件怎么样 编辑:程序博客网 时间:2024/04/29 22:45
第一中创建单例的代码:
//使用allocWithZone[经典方式]方式创建,需要具备三部分
//1、类的构造方法是私有的--我们只需要重写allocWithZone方法,让初始化操作只执行一次
//2、类提供一个类方法用于生产对象--这个可以直接定义一个类方法
//3、类中有一个私有的自己对象--在.m文件中定义一个属性即可
//创建私有对象
static Why *why =nil;
//自身产生对象提供给外部使用
+(Why *)shareInstance
{
if (why ==nil) {
why = [[Whyalloc]init];
}
return why;
}
//限制方法,类只能初始化一次,在alloc的时候会调用
+ (id)allocWithZone:(struct_NSZone *)zone
{
// if (why == nil) {
// why = [super allocWithZone:zone];
// }
// return why;
if (!why) {
why = [superallocWithZone:zone];
}
return why;
}
//拷贝方法
- (id)copyWithZone:(NSZone *)zone
{
return why;
}
第二种创建单例的方法-使用线程加锁[GCD]的方式进行创建单例,该方法比较常用
+ (Why *)shareInstance2
{
static Why *w;
// 断言,确定是否执行代码块,断言的指针要保存起来,必须全句化保存或者是放在静态区内,使用存放在自动分配区域或动态分配区域的断言,dispatch_once执行的结果是不可预知的
static dispatch_once_t onceToken;
dispatch_once(&onceToken,^{
w = [[[self class] alloc] init];
});
return w;
}
第三种创建单例
使用指令锁的方式,锁住线程不让别人访问
static WHY *instance = nil;
+ (WHY *)Instance
{
@synchronized(self)
{
if(instance == nil){
instance = [[self alloc] init];
}
}
return instance;
}