#import <Foundation/Foundation.h>
@interface Single : NSObject
@property (nonatomic,copy)NSString *value;
+(Single *)SingleModel;
@end
#import "Single.h"
@implementation Single
static Single *single =nil;
+ (Single *)SingleModel
{
//block内代码只会被执行一次 是否被执行 是由once来记录
static dispatch_once_t once;
dispatch_once(&once, ^{
single =[[Single alloc] init];
});
return single;
}
+ (id)allocWithZone:(struct _NSZone *)zone
{
static dispatch_once_t once;
dispatch_once(&once, ^{
single =[super allocWithZone:NULL];
});
return single;
}
另外 两种加锁方式
@implementation Single
static Single * single =nil;
+ (Single *)SingleModel
{
//@synchronized 资源保护锁 防止多线程操作时 对同一资源访问时造成资源混乱而设定的
//()标示符 代表类 或者使用对象类型 一般使用self
@synchronized (self)
{
if (single==nil)
{
single =[[Single alloc] init];
}
}
return single;
}
+ (id)allocWithZone:(struct _NSZone *)zone
{
//NSLock 一种加锁的形式 和 @synchronized (self)效果一样
if (single ==nil)
{
NSLock *lock =[[NSLock alloc] init];
//[lock lock]和[lock unlock]之间的代码就是要保护的资源
[lock lock];
single = [super allocWithZone:NULL];
[lock unlock];
}
return single;
}