#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內(nèi)代碼只會被執(zhí)行一次 是否被執(zhí)行 是由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 資源保護鎖 防止多線程操作時 對同一資源訪問時造成資源混亂而設(shè)定的
//()標(biāo)示符 代表類 或者使用對象類型 一般使用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;
}