单利宏的实现

来源:互联网 发布:最新台风下载软件 编辑:程序博客网 时间:2024/06/09 23:31


.h 文件 写 SingletonH(MyMethodName) 

.m 文件写 SingletonM(MyMethodName)



// 帮助实现单例设计模式


// .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


0 0
原创粉丝点击