码迷,mamicode.com
首页 > 移动开发 > 详细

iOS开发之自定义一个单例

时间:2015-04-24 22:27:09      阅读:214      评论:0      收藏:0      [点我收藏+]

标签:

iOS开发之自定义一个单例

这里我使用宏:

// .h
#define single_interface(class)  + (class *)shared##class;

// .m
// \ 代表下一行也属于宏
// ## 是分隔符

  • #define single_implementation(class) \
  • static class *_instance; \
  •  \
  • + (class *)shared##class \
  • { \
  •     if (_instance == nil) { \
  •         _instance = [[self alloc] init]; \
  •     } \
  •     return _instance; \
  • } \
  •  \
  • + (id)allocWithZone:(NSZone *)zone \
  • { \
  •     static dispatch_once_t onceToken; \
  •     dispatch_once(&onceToken, ^{ \
  •         _instance = [super allocWithZone:zone]; \
  •     }); \
  •     return _instance; \
  • }
 当然还有其他更全面的方法,但是上面喝上吗的原理都是一样的,平时使用的实用用上面的就可以。

//单例模式在ARC\MRC环境下的写法有所不同,需要编写2套不同的代码
#if  __has_feature(objc_arc)
//ARC

//重写allocWithZone:方法,在这里创建唯一的实例(注意线程安全)
  • + (id)allocWithZone:(struct _NSZone *)zone
  • {
  •     @synchronized(self) {
  •     if (!_instance) {
  •             _instance = [super allocWithZone:zone];
  •         }
  •     }
  •     return _instance;
  • }
  • //提供1个类方法让外界访问唯一的实例
  • + (instancetype)shareInstance
  • {
  •     @synchronized(self) {
  •         if (!_instance) {
  •             _instance = [[self alloc] init];
  •         }
  •     }
  •     return _instance;
  • }
  • //实现copyWithZone:方法
  • + (id)copyWithZone:(struct _NSZone *)zone
  • {
  •     return _instance;
  • }

#else
//非ARC

 //非ARC中(MRC),单例模式的实现(比ARC多了几个步骤)


//重写allocWithZone:方法,在这里创建唯一的实例(注意线程安全)
  • + (id)allocWithZone:(struct _NSZone *)zone
  • {    @synchronized(self) {
  •     if (!_instance) {
  •         _instance = [super allocWithZone:zone];
  •     }
  • }
  •     return _instance;
  • }
  • //提供1个类方法让外界访问唯一的实例
  • + (instancetype)shareInstance
  • {
  •     @synchronized(self) {
  •         if (!_instance) {
  •             _instance = [[self alloc] init];
  •         }
  •     }
  •     return _instance;
  • }
  • //实现copyWithZone:方法
  • + (id)copyWithZone:(struct _NSZone *)zone
  • {
  •     return _instance;
  • }
  •  //实现内存管理方法
  • - (id)retain
  • {
  •     return self;
  • }
  • - (NSUInteger)retainCount
  • {
  •     return 1;
  • }
  •  
  • - (oneway void)release
  • {
  • }
  •  
  •  - (id)autorelease
  • {
  •     return self;
  • }

#endif

 

iOS开发之自定义一个单例

标签:

原文地址:http://www.cnblogs.com/iCocos/p/4454432.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!