单例的实现

1.    MRC中实现单例

创建单例设计模式的基本步骤

1> 声明一个单例对象的静态实例,并初始化为nil。

2> 创建一个类的类工厂方法,当且仅当这个类的实例为nil时生成一个该类的实例

3> 实现NScopying协议, 覆盖allocWithZone:方法,确保用户在直接分配和初始化对象时,不会产生另一个对象。

4> 覆盖release、autorelease、retain、retainCount方法, 以此确保单例的状态。

1>    在多线程的环境中,注意使用@synchronized关键字或GCD,确保静态实例被正确的创建和初始化。

2> // 单例的方法 解决资源抢夺问题

+ (id)allocWithZone:(struct _NSZone *)zone

{

    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        _instance = [super allocWithZone:zone];

    });

 

    return _instance;

}

3>    单例创建的时候,提供shared或者类方法



以下为ARC和MRC中实现单例方法的宏定义



// 帮助实现单例设计模式


// .h文件的实现

#define SingletonH(methodName) + (instancetype)shared##methodName;


// .m文件的实现

#if __has_feature(objc_arc) // ARC

#define SingletonM(methodName) \

static id _instace = nil; \

+ (id)allocWithZone:(struct _NSZone *)zone \

{ \

if (_instace == nil) { \

static dispatch_once_t onceToken; \

dispatch_once(&onceToken, ^{ \

_instace = [super allocWithZone:zone]; \

}); \

} \

return _instace; \

} \

\

- (id)init \

{ \

static dispatch_once_t onceToken; \

dispatch_once(&onceToken, ^{ \

_instace = [super init]; \

}); \

return _instace; \

} \

\

+ (instancetype)shared##methodName \

{ \

return [[self alloc] init]; \

} \

+ (id)copyWithZone:(struct _NSZone *)zone \

{ \

return _instace; \

} \

\

+ (id)mutableCopyWithZone:(struct _NSZone *)zone \

{ \

return _instace; \

}


#else // 不是ARC


#define SingletonM(methodName) \

static id _instace = nil; \

+ (id)allocWithZone:(struct _NSZone *)zone \

{ \

if (_instace == nil) { \

static dispatch_once_t onceToken; \

dispatch_once(&onceToken, ^{ \

_instace = [super allocWithZone:zone]; \

}); \

} \

return _instace; \

} \

\

- (id)init \

{ \

static dispatch_once_t onceToken; \

dispatch_once(&onceToken, ^{ \

_instace = [super init]; \

}); \

return _instace; \

} \

\

+ (instancetype)shared##methodName \

{ \

return [[self alloc] init]; \

} \

\

- (oneway void)release \

{ \

\

} \

\

- (id)retain \

{ \

return self; \

} \

\

- (NSUInteger)retainCount \

{ \

return 1; \

} \

+ (id)copyWithZone:(struct _NSZone *)zone \

{ \

    return _instace; \

} \

 \

+ (id)mutableCopyWithZone:(struct _NSZone *)zone \

{ \

    return _instace; \

}


#endif

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值