单例

单例ARC和MRC写法

1:什么是单例模式?

 

  • 类的对象成为系统中唯一的实例,提供一个访问点,供客户类 共享资源
  • 单例就是无论怎么创建都只能有一个实例对象

2:什么情况下使用单例?

 

  1. 类只能有一个实例,而且必须从一个为人熟知的访问点对其进行访问,比如工厂方法。
  2. 这个唯一的实例只能通过子类化进行扩展,而且扩展的对象不会破坏客户端代码。

3:创建单例对象的方法一般以什么开头?

 

  1. 一般情况下创建一个单例对象都有一个与之对应的类方法
  2. 一般情况下用于创建单例对象的方法名称都以share开头, 或者以default开头

4:单例在多线程的应用?

多线程中的单例

+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
    // 以下代码在多线程中也能保证只执行一次
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[super allocWithZone:zone] init];
    });
    return _instance;
}

 

 

22.单例宏抽取

1:如何将单例抽取成宏?如何在宏中判断当前是ARC还是MRC?

 

  • 单例宏定义
  • 以后就可以使用interfaceSingleton来替代后面的方法声明
#define interfaceSingleton(name)  +(instancetype)share##name

#if __has_feature(objc_arc)
// ARC
#define implementationSingleton(name)  \
+ (instancetype)share##name \
{ \
name *instance = [[self alloc] init]; \
return instance; \
} \
static name *_instance = nil; \
+ (instancetype)allocWithZone:(struct _NSZone *)zone \
{ \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instance = [[super allocWithZone:zone] init]; \
}); \
return _instance; \
} \
- (id)copyWithZone:(NSZone *)zone{ \
return _instance; \
} \
- (id)mutableCopyWithZone:(NSZone *)zone \
{ \
,return _instance; \
}
#else
// MRC

#define implementationSingleton(name)  \
+ (instancetype)share##name \
{ \
name *instance = [[self alloc] init]; \
return instance; \
} \
static name *_instance = nil; \
+ (instancetype)allocWithZone:(struct _NSZone *)zone \
{ \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instance = [[super allocWithZone:zone] init]; \
}); \
return _instance; \
} \
- (id)copyWithZone:(NSZone *)zone{ \
return _instance; \
} \
- (id)mutableCopyWithZone:(NSZone *)zone \
{ \
return _instance; \
} \
- (oneway void)release \
{ \
} \
- (instancetype)retain \
{ \
return _instance; \
} \
- (NSUInteger)retainCount \
{ \
return  MAXFLOAT; \
}
#endif

 

转载于:https://www.cnblogs.com/dreamWanweidong/p/4998813.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值