iOS 单例宏定义记录

2020-03-23  本文已影响0人  Her0cheN

MYSingleton.h : 单例宏定义 - 头文件

// 使用方法:.h 添加
// MYSingletonH(SingletonClass)//单例模式
// 使用方法:.m 添加
// MYSingletonM(SingletonClass)//单例模式


// MYSingletonH.h文件 - 创建MYSingletonH.h全局文件
#define MYSingletonH(name) + (instancetype)shared##name;

#if __has_feature(objc_arc)

    #define MYSingletonM(name) \
    static id _instace; \
 \
    + (id)allocWithZone:(struct _NSZone *)zone \
    { \
        if (_instace == nil) {\
            _instace = [super allocWithZone:zone]; \
            NSLog(@"单例创建!--- 上架删除该行"); \
        } \
        return _instace; \
    } \
 \
    + (instancetype)shared##name \
    { \
        if (_instace == nil) {\
            _instace = [[self alloc]init]; \
        } \
      return _instace; \
  \
    } \
 \
    - (id)copyWithZone:(NSZone *)zone \
    { \
        return _instace; \
    }

#else

    #define MYSingletonM(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

上一篇 下一篇

猜你喜欢

热点阅读