oc单例模式

一: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。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值