iOS单例模式宏文件

如何使用?创建一个单例对象

  1. 引入头文件#import MGSingleton.h
  2. HttpTool.h头文件添加MGSingletonH(HttpTool)
  3. HttpTool.m中添加MGSingletonM(HttpTool)
  4. 使用时创建一个单例:HttpTool *tool = [HttpTool sharedHttpTool];

注意点

  • ##是宏拼接参数,传入什么,它就是什么
  • 每一行最后加\识别继续下一行,最后一行代码不用加\
  • 要把注释删掉,中间不能有注释
  • 判断是不是arc环境 __has_feature(objc_arc)

宏文件,同时兼容ARC和MRC

  • MGSingleton.h文件
#define MGSingletonH(name)  +(instancetype)shared##name;
  • MGSingleton.m文件
#if __has_feature(objc_arc)

#define MGSingletonM(name) \
static id _instace; \
\
+ (id)allocWithZone:(struct _NSZone *)zone \
{ \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instace = [super allocWithZone:zone]; \
}); \
return _instace; \
} \
\
+ (instancetype)shared##name \
{ \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instace = [[self alloc] init]; \
}); \
return _instace; \
} \
\
- (id)copyWithZone:(NSZone *)zone \
{ \
return _instace; \
}

#else

#define MGSingletonM(name) \
static id _instace; \
\
+ (id)allocWithZone:(struct _NSZone *)zone \
{ \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instace = [super allocWithZone:zone]; \
}); \
return _instace; \
} \
\
+ (instancetype)shared##name \
{ \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instace = [[self alloc] init]; \
}); \
return _instace; \
} \
\
- (id)copyWithZone:(NSZone *)zone \
{ \
return _instace; \
} \
\
- (oneway void)release { } \
- (id)retain { return self; } \
- (NSUInteger)retainCount { return 1;} \
- (id)autorelease { return self;}

#endif

MRC下retain返回本身,release不做事情,retainCount返回1、autorelease返回自己

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • *面试心声:其实这些题本人都没怎么背,但是在上海 两周半 面了大约10家 收到差不多3个offer,总结起来就是把...
    Dove_iOS阅读 27,219评论 30 472
  • 在iOS中有很多的设计模式,有一本书《Elements of Reusable Object-Oriented S...
    郑明明阅读 2,469评论 3 26
  • 1 单例模式 它是一种设计模式(常见的设计模式有:观察者模式、工厂模式、门面模式等)。单例设计模式中,一个类只有一...
    岁与禾阅读 930评论 5 9
  • 单例一般作为:工具类 单例命名:一般情况下如果一个类是单例,那么就要提供一个类方法用于快速创建单例对象,而且这个类...
    甘哲157阅读 1,799评论 0 15
  • 1,NSObject中description属性的意义,它可以重写吗?答案:每当 NSLog(@"")函数中出现 ...
    eightzg阅读 4,197评论 2 19