您的位置:首页 > 其它

单例宏

2015-11-26 21:12 363 查看
//
帮助实现单例设计模式

// .h文件的实现

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

// .m文件的实现

#if __has_feature(objc_arc)
//
是ARC

#define SingletonM(methodName) \

static id _instace = nil; \

+ (id)allocWithZone:(struct _NSZone *)zone \

{ \

if (_instace == nil) { \

static dispatch_once_t onceToken; \

dispatch_once(&onceToken, ^{ \

_instace = [super allocWithZone:zone]; \

}); \

} \

return _instace; \

} \

\

- (id)init \

{ \

static dispatch_once_t onceToken; \

dispatch_once(&onceToken, ^{ \

_instace = [super init]; \

}); \

return _instace; \

} \

\

+ (instancetype)shared##methodName \

{ \

return [[self alloc] init]; \

} \

+ (id)copyWithZone:(struct _NSZone *)zone \

{ \

return _instace; \

} \

\

+ (id)mutableCopyWithZone:(struct _NSZone *)zone \

{ \

return _instace; \

}

#else
//
不是ARC

#define SingletonM(methodName) \

static id _instace = nil; \

+ (id)allocWithZone:(struct _NSZone *)zone \

{ \

if (_instace == nil) { \

static dispatch_once_t onceToken; \

dispatch_once(&onceToken, ^{ \

_instace = [super allocWithZone:zone]; \

}); \

} \

return _instace; \

} \

\

- (id)init \

{ \

static dispatch_once_t onceToken; \

dispatch_once(&onceToken, ^{ \

_instace = [super init]; \

}); \

return _instace; \

} \

\

+ (instancetype)shared##methodName \

{ \

return [[self alloc] init]; \

} \

\

- (oneway void)release \

{ \

\

} \

\

- (id)retain \

{ \

return self; \

} \

\

- (NSUInteger)retainCount \

{ \

return
1; \

} \

+ (id)copyWithZone:(struct _NSZone *)zone \

{ \

return _instace; \

} \

\

+ (id)mutableCopyWithZone:(struct _NSZone *)zone \

{ \

return _instace; \

}

#endif
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: