单例模式-用GCD实现

时间:2024-12-04 09:35:38

用GCD实现单例模式的步骤:

步骤1. 创建头文件 XZSingleton.h,里面代码如下:

// .h文件
#define XZSingletonH(name) + (instancetype)shared##name; // .m文件
#if __has_feature(objc_arc) #define XZSingletonM(name) \
static id _instace; \
\
+ (id)allocWithZone:(struct _NSZone *)zone \
{ \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instace = [super allocWithZone:zone]; \
}); \
return _instace; \
} \
\
+ (instancetype)shared##name \
{ \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instace = [[self alloc] init]; \
}); \
return _instace; \
} \
\
- (id)copyWithZone:(NSZone *)zone \
{ \
return _instace; \
} #else #define XZSingletonM(name) \
static id _instace; \
\
+ (id)allocWithZone:(struct _NSZone *)zone \
{ \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instace = [super allocWithZone:zone]; \
}); \
return _instace; \
} \
\
+ (instancetype)shared##name \
{ \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instace = [[self alloc] init]; \
}); \
return _instace; \
} \
\
- (id)copyWithZone:(NSZone *)zone \
{ \
return _instace; \
} \
\
- (oneway void)release { } \
- (id)retain { return self; } \
- (NSUInteger)retainCount { return ;} \
- (id)autorelease { return self;} #endif

步骤2. 要实现的单例类,比如 XZDataTool,XZDataTool.h   XZDataTool.m代码分别 如下:

#import <Foundation/Foundation.h>

@interface XZDataTool : NSObject
XZSingletonH(DataTool)
@end
#import "XZDataTool.h"

@implementation XZDataTool
XZSingletonM(DataTool)
@end