最方便,好用的单例—实现一行代码创建单例

40 篇文章 0 订阅
  • 一般来说,我们在一个类中写单例,要是想考虑的全面,那么要考虑到各个因素。
  • 因为我们不知道别人创建单例的时候,通过什么创建的。所以我们就必须把通过各个方式创建的单例,都写出来:
+(instancetype)sharedSoundTool{
    static id instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    return instance;
}
//
 + (instancetype)allocWithZone:(struct _NSZone *)zone {
    static id instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [super allocWithZone:zone];
    });
    return instance;
}
//
 + (id)copyWithZone:(nullable NSZone *)zone{
    return self;
}
//
#pragma mark - 在非ARC环境下,还要重写下面方法
 + (oneway void)release {
}
//
 + (instancetype)autorelease {
    return self;
}
//
 + (instancetype)retain {
    return self;
}
//
 + (NSUInteger)retainCount {
    return 1;
}
  • 这应该是最全面的单例的创建了吧,包括了各个方面,各个方式。

然后我们抽取到一个.h文件中:

#define ZYSingleton_h(name)  +(instancetype)shared##name;


#if __has_feature(objc_arc) // arc环境
#define ZYSingleton_m(name)  +(instancetype)shared##name{ \
static id instance = nil; \
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
instance = [[self alloc] init];\
});\
return instance;\
}\
\
+ (instancetype)allocWithZone:(struct _NSZone *)zone {\
static id instance = nil;\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
instance = [super allocWithZone:zone];\
});\
return instance;\
}\
\
- (id)copyWithZone:(nullable NSZone *)zone{\
return self;\
}
#else // 非arc环境

#define ZYSingleton_m(name)  +(instancetype)shared##name{ \
static id instance = nil; \
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
instance = [[self alloc] init];\
});\
return instance;\
}\
\
 + (instancetype)allocWithZone:(struct _NSZone *)zone {\
static id instance = nil;\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
instance = [super allocWithZone:zone];\
});\
return instance;\
}\
\
 + (id)copyWithZone:(nullable NSZone *)zone{\
return self;\
}\
 + (oneway void)release {\
}\
\
 + (instancetype)autorelease {\
    return self;\
}\
\
 + (instancetype)retain {\
    return self;\
}\
\
 + (NSUInteger)retainCount {\
    return 1;\
}
#endif
  • 接下来使用起来就非常爽了:
  • 现在我们想创建一个单例对象:

在.h文件中

#import "ZYSingleton.h"
@interface ZYHttpTool : NSObject

ZYSingleton_h(HttpTool)
@end

.m文件中:

@implementation ZYHttpTool
ZYSingleton_m(HttpTool);
@end

就完成了一个单例的创建,就是这么easy

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值