iOS 开发

iOS 常用单例宏

2016-06-29  本文已影响96人  CodeGeass

在你的宏文件里面加入单例宏,快捷创建单例

#define SINGLETON_INTERFACE(className) + (instancetype)shared##className;

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

调用

.h

SINGLETON_INTERFACE(Service)

.m

SINGLETON_IMPLEMENTATION(Service)
上一篇下一篇

猜你喜欢

热点阅读