单例 宏定义

版权声明:本文为延成原创文章,转载请标明出处

#define interfaceSingleton(name) +(instancetype)share##name

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

#else
#define implementationSingleton(name) \
+ (instancetype)share##name{ \
     return [[self alloc]init]; \
} \
static name *_instance = nil; \
+ (instancetype)allocWithZone:(struct _NSZone *)zone{ \
    static dispatch_once_t onceToken; \
       dispatch_once(&onceToken, ^{ \
           _instance = [[super allocWithZone:zone]init]; \
       }); \
       return _instance; \
} \
- (nonnull id)copyWithZone:(nullable NSZone *)zone { \
    return _instance; \
} \
- (nonnull id)mutableCopyWithZone:(nullable NSZone *)zone { \
    return _instance; \
} \
- (oneway void)release{ \
} \
- (instancetype)retain{ \
    return _instance; \
} \
- (NSUInteger)retainCount{ \
    return MAXFLOAT; \
} \

#endif
发布了152 篇原创文章 · 获赞 23 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/AliEnCheng/article/details/103972045