单例模式
目录
- 概述——对单例模式的理解
- OC上的单例模式
- 多线程中的单例模式
线程安全实现一
线程安全苹果官方实现
使用GCD实现单例模式(推荐使用)
- 单例模式的运用
概述——对单例模式的理解
OC上的单例模式
@implementation Singleton
static Singleton *singleton;
+(id)sharedInstance{
if(!singleton){
singleton = [[Singleton alloc] init];
}
return singleton;
}
@end
多线程中的单例模式
线程安全实现一
+(id)sharedInstance{
@synchronized(self){
if(!singleton){
singleton = [[Singleton alloc] init];
}
}
return singleton;
}
线程安全苹果官方实现
+(id)sharedInstance{
@synchronized(self){
if(singleton == nil){
[[self alloc] init]; //assignment not done here
}
}
}
+(id)allocWithZone:(NSZone *)zone{
@synchronized(self){
if(singleton == nil){
singleton == [super allocWithZone:zone];
return singleton; //assignment and return on first allocation
}
}
return nil; //on subsequent allocation attempts return nil
}
-(id)copyWithZone:(NSZone *)zone{
return self;
}
-(id)retain{
return self;
}
-(unsigned)retainCount{
return UINT_MAX; //denotes an object that cannot be released
}
-(void)release{
}
-(id)autorelease{
return self;
}
注释
使用@synchronized( )指令可以锁住在线程中执行的某一个代码块
@synchronized()指令的唯一参数可以使用任何OC对象,包括self。这个对象就是我们所谓的信号量
最安全的是,在应用程序进入多线程之前,为所有需要互斥的创建互斥信号量
使用GCD实现单例模式(推荐使用)
+ (IQKeyboardManager*)sharedManager
{
//Singleton instance
static IQKeyboardManager *kbManager;
//Dispatching it once.
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
// Initializing keyboard manger.
kbManager = [[self alloc] init];
});
//Returning kbManager.
return kbManager;
}
-(id)init
{
if (self = [super init])
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
}
}
}
单例模式的运用