A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© wanyiyuan 中级黑马   /  2014-9-19 01:32  /  1645 人查看  /  4 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

其实在OC中有好多单例的例子例如    [UIApplication sharedApplication];
    [NSUserDefaults standardUserDefaults];
    ......还有很多
废话不多说,直接上代码
  • // .h文件的实现
  • //定义一个宏 shared##methodName 加## 是为了能够更改methodName方法体名称
  • #define SingletonH(methodName) + (instancetype)shared##methodName;
  • // .m文件的实现
  • #if __has_feature(objc_arc) // ARC,这里判断的是ARC还是非ARC
  • #define SingletonM(methodName) \
  • static id _instace = nil; \
  • + (id)allocWithZone:(struct _NSZone *)zone \//重写allocWithZone方法
  • { \
  • if (_instace == nil) { \//懒加载
  • static dispatch_once_t onceToken; \//保证实例化出来的对象的唯一性
  • dispatch_once(&onceToken, ^{ \
  • _instace = [super allocWithZone:zone]; \//调用父类的allocWithZone方法
  • }); \
  • } \
  • return _instace; \//返回实例
  • } \
  • \
  • - (id)init \//重写ini方法
  • { \
  • 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 \//重写copyWithZone方
  • { \
  • return _instace; \
  • } \
  • \
  • + (id)mutableCopyWithZone:(struct _NSZone *)zone \//重写mutableCopyWithZone方法
  • { \
  • 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 \//镂空release方法,保证对象的计数器一直为1,
  • { \
  • } \
  • - (id)retain \//重写retain方法
  • { \
  • return self; \
  • } \
  • - (NSUInteger)retainCount \//重写retainCount方法
  • { \
  • return 1; \
  • } \
  • + (id)copyWithZone:(struct _NSZone *)zone \
  • { \
  • return _instace; \
  • } \
  • + (id)mutableCopyWithZone:(struct _NSZone *)zone \
  • { \
  • return _instace; \
  • }
  • #endif

直接上图吧



点评

转的就说转的嘛,连变量名都一模一样http://www.cnblogs.com/xyzaijing/p/3855649.html  发表于 2014-9-19 03:10

4 个回复

倒序浏览
此帖仅作者可见
使用道具 举报
此帖仅作者可见
使用道具 举报
此帖仅作者可见
使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马