现创建XMGPerson文件
#import "XMGPerson.h"
//严禁起见,用到copy
@interface XMGPerson ()<NSCopying> //签协议,调- (id)copyWithZone:(NSZone *)zone;方法
@end
@implementation XMGPerson
static XMGPerson *_person;
//目的:调多少次,都是一个person
+(instancetype)allocWithZone:(struct _NSZone *)zone{
//分配内存
//重写allect init的目的是同一个person
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_person = [super allocWithZone:zone];
});
return _person;
}
+ (instancetype)share{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
// 目的:调多少次,只alloc init一次
_person = [[self alloc]init];//支调一次
});
return _person;
}
//+是类方法。-是对象方法
- (id)copyWithZone:(NSZone *)zone{
return _person;
}
@end
#import <Foundation/Foundation.h>
@interface XMGPerson : NSObject
+ (instancetype)share;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// NSLog(@"%@,%@",[XMGPerson share],[[XMGPerson alloc]init]);
//打印的结果是一样的,原因看目的一,二
XMGPerson *p = [XMGPerson share];
XMGPerson *p2 = [p copy];//完整的单列,在XMGPerson里添加了@interface XMGPerson ()<NSCopying>@end和- (id)copyWithZone:(NSZone *)zone{return _person;
}