iOS 常用单例宏

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

#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)

你可能感兴趣的:(iOS 常用单例宏)