#import <Foundation/Foundation.h>
@interface Tool : NSObject<NSCopying,NSMutableCopying>
//提供一个类方法,方便外接访问
/*
1.方便外接访问
2.表明身份,说明我是一个单例
3.注意点:规范~share+类名|default+类名|share|类名
*/
+(instancetype)shareTool;
@end
#import "Tool.h"
@implementation Tool
//1.提供一个静态变量
static Tool *_instance;
//2.重写该方法
+(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;
}
//3.提供一个类方法
+(instancetype)shareTool
{
return [[self alloc]init];
}
//4.重写copy方法
-(id)copyWithZone:(NSZone *)zone
{
return _instance;
}
-(id)mutableCopyWithZone:(NSZone *)zone
{
return _instance;
}
@end