美文网首页
OC - iOS - 宏单例

OC - iOS - 宏单例

作者: 黎希 | 来源:发表于2016-08-04 11:19 被阅读31次

Macro单例


// .h文件的实现

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

// .m文件实现
#if __has_feature(objc_arc) // ARC下

#define SingletonM(methodName)\
static id _instance = nil;\
+ (instancetype)allocWithZone:(struct _NSZone *)zone{\
if (!_instance) {\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
_instance = [super allocWithZone:zone];\
});\
}\
return _instance;\
}\
\
- (instancetype)init{\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
_instance = [super init];\
});\
return _instance;\
}\
\
+ (instancetype)share##methodName{\
return [[self alloc] init];\
}\
\
- (id)copyWithZone:(NSZone *)zone {\
return _instance;\
}\
+ (id)copyWithZone:(struct _NSZone *)zone {\
return _instance;\
}\
- (id)mutableCopyWithZone:(NSZone *)zone {\
return _instance;\
}\
+ (id)mutableCopyWithZone:(struct _NSZone *)zone {\
return _instance;\
}

#else
// 非ARC下
#define SingletonM(methodName)\
static id _instance = nil;\
+ (instancetype)allocWithZone:(struct _NSZone *)zone{\
    if (!_instance) {\
        static dispatch_once_t onceToken;\
        dispatch_once(&onceToken, ^{\
            _instance = [super allocWithZone:zone];\
        });\
    }\
    return _instance;\
}\
\
- (instancetype)init{\
    static dispatch_once_t onceToken;\
    dispatch_once(&onceToken, ^{\
        _instance = [super init];\
    });\
    return _instance;\
}\
\
+ (instancetype)share##methodName{\
    return [[self alloc] init];\
}\
\
- (id)copyWithZone:(NSZone *)zone {\
return _instance;\
}\
+ (id)copyWithZone:(struct _NSZone *)zone {\
    return _instance;\
}\
- (id)mutableCopyWithZone:(NSZone *)zone {\
    return _instance;\
}\
+ (id)mutableCopyWithZone:(struct _NSZone *)zone {\
    return _instance;\
}\
- (oneway void)release{\
   \
}\
\
- (instancetype)retain{\
    return self;\
}\
\
- (NSUInteger)retainCount{\
    return 1;\
}

#endif

相关文章

  • OC - iOS - 宏单例

    Macro单例

  • IOS OC 单例宏

  • ios~单例模式:

    在iOS OC中,一般我们都是用官方推荐的写法来写单例:GCD方式单例 分析单例 static SharedPer...

  • 单例模式的书写

    ARC OC 中的单例 根据OC单例 改写成 Swift 中的单例 OC调用swift,需要#import "单例...

  • ios 单例宏

    单例的初始化在整个app生命周期内(非对象的生命周期)只执行一次,本文介绍通过宏来实现单例方法的定义。代码如下:-...

  • iOS单例宏

    开发中我们无可避免的使用到单例,单例的具体作用不多说了,这里记录一下单例宏的写法。新建一个header file,...

  • iOS 单例宏

    #if __has_feature(objc_arc) #define SYNTHESIZE_SINGLETON_...

  • 单例

    单例 单例宏

  • swiftly单例

    swiftly的单例比OC的更加简单! Oc中的单例:

  • 单例

    iOS单例模式iOS之单例模式初探iOS单例详解

网友评论

      本文标题:OC - iOS - 宏单例

      本文链接:https://www.haomeiwen.com/subject/fpkzdttx.html