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

iOS单例宏

时间:2014-08-17 01:14:21      阅读:258      评论:0      收藏:0      [点我收藏+]

标签:http   使用   os   io   文件   数据   ar   问题   

先别急,先简单提一下单列的概念,当然具体的描述可能仁者见仁智者见智了!
1.单例设计模式(Singleton)
1> 什么是单列: 它可以保证某个类创建出来的对象永远只有1个

2> 作用(为什么要用)

  • 节省内存开销
  • 如果有一些数据, 整个程序中都用得上, 只需要使用同一份资源(保证大家访问的数据是相同的,一致的)
  • 一般来说, 工具类设计为单例模式比较合适

3> 怎么实现,老程序员是碰到这样的问题的!arc下就少了!

  • MRC(非ARC)
  • ARC

废话少说,先来看一下我的单例模式下的头文件! 这里主要是__has_feature(objc_arc) 判断了一下是否为arc,所以代码看上去有点多!

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

// .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

这个里面完完全全的做到了,单列所有情况的考虑,包括copy情况,多线程,还有自动判断ARC和MRC情况!
用的时候只需要在包含头文件然后是用下面
.h文件下:SingletonH(HttpTool)
.m文件下:SingletonM(HttpTool)

这东西谁用谁知道!!!!嘻嘻!希望对读者有帮助!

iOS单例宏,布布扣,bubuko.com

iOS单例宏

标签:http   使用   os   io   文件   数据   ar   问题   

原文地址:http://my.oschina.net/panyong/blog/302502

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