单例的作用和功能这里不想在多说,相信大家都已经比较了解,这里直接写单利类.m文件中的代码(适配了arc和mrc)
@interface HTUser : NSObject+ (instancetype)shareHTUser;
@end
@implementation HTUser
static HTUser *_instance; //这里static表示_instance这个变量只能在该类中使用。
+(instancetype)allocWithZone:(struct _NSZone *)zone{
@synchronized (self) {
if (_instance==nil) {
_instance = [super allocWithZone:zone];
}
}
//或者 下面这中写法性能更加好
// static dispatch_once_t onceToken;
// dispatch_once(&onceToken, ^{
// _instance = [super allocWithZone:zone];
// });
return _instance;
}
+ (instancetype)shareHTUser{
//最好写成self 加入是类型 则这个类的子类无法使用
return [[self alloc] init];
}
-(id)copyWithZone:(NSZone *)zone{
return _instance;
}
- (id)mutableCopyWithZone:(NSZone *)zone{
return _instance;
}
#if __has_feature(objc_arc)
//arc
#else
//mrc
-(oneway void)release{
}
-(instancetype)retain{
return _instance;
}
-(NSUInteger)retainCount{
return MAXFLOAT; //返回最大值 让其他人知道这个类是单利
}
#endif
@end
因为单例的代码大多数代码是一样的,所以单例的代码也可以用宏来表示
#define singleH(name) + (instancetype)share##name;
#if __has_feature(objc_arc)
#define singleM(name) static id _instance;\
+(instancetype)allocWithZone:(struct _NSZone *)zone{\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
_instance = [super allocWithZone:zone];\
});\
return _instance;\
}\
+ (instancetype)share##name{\
return [[self alloc] init];\
}\
-(id)copyWithZone:(NSZone *)zone{\
return _instance;\
}\
- (id)mutableCopyWithZone:(NSZone *)zone{\
return _instance;\
}
#else
#define singleM(name) static id _instance;\
+(instancetype)allocWithZone:(struct _NSZone *)zone{\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
_instance = [super allocWithZone:zone];\
});\
return _instance;\
}\
+ (instancetype)share##name{\
return [[self alloc] init];\
}\
-(id)copyWithZone:(NSZone *)zone{\
return _instance;\
}\
- (id)mutableCopyWithZone:(NSZone *)zone{\
return _instance;\
}\
-(oneway void)release{\
}\
-(instancetype)retain{\
return _instance;\
}\
-(NSUInteger)retainCount{\
return MAXFLOAT;\
}
#endif
网友评论