一:gcd代码
.h文件
#import <Foundation/Foundation.h>
@interface JSCPlaySound : NSObject
+ (JSCPlaySound *)shareInstance;
@end
.m文件
#import "JSCPlaySound.h"
@implementation JSCPlaySound
+ (JSCPlaySound *)shareInstance{
static JSCPlaySound *_instance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instance = [[self alloc]init];
});
return _instance;
}
@end
二:非gcd代码
.h文件
#import <Foundation/Foundation.h>
@interface JSCPlaySound : NSObject
+ (JSCPlaySound *)shareInstance;
@end
.m文件
#import "JSCPlaySound.h"
static JSCPlaySound *_instance = nil;
@implementation JSCPlaySound
+ (JSCPlaySound *)shareInstance{
if (_instance==nil) {
_instance = [[JSCPlaySound alloc] init];
}
return _instance;
}
+(id) allocWithZone:(struct _NSZone *)zone
{
return [JSCPlaySound shareInstance] ;
}
@end
第一种方法有很多优势,首先满足了线程安全问题,其次很好满足静态分析器要求。GCD可以确保以更快的方式完成这些检测,它可以保证block中的代码在任何线程通过dispatch_once调用之前被执行,但它不会强制每次调用这个函数都让代码进行同步控制。实际上,如果你去看这个函数所在的头文件,你会发现目前它的实现其实是一个宏,进行了内联的初始化测试,这意味着通常情况下,你不用付出函数调用的负载代价,并且会有更少的同步控制负载。
因此,以后我们使用单例模式的时候尽量使用GCD。