Student.h
#import??
@interface?Student :?NSObject?
@property(nonatomic,copy)NSString?*name;?
//1、在h文件中公告一个类方法,用于初始化实例
+(id)shareStudent;
@end
Student.m
#import?”Student.h”?
//2、在.m文件中首先公告一个static修饰的对象,此对象此时是一个空指针
static?Student?*stu =?nil;?
@implementation?Student?
//3、实现.h中公告的类方法
+(id)shareStudent{
?//避免多线程操作带来的弊端 ?(互斥锁)?
?@synchronized(self){
?if?(stu?==?nil) {
?stu?= [[Student?alloc]init];
}
?return?stu;
}
}
或者者:
dispatch_once(&onceToken,?^{
????????if(Student?==?nil)?{
????????????stu?=?[[Student?alloc]?init];
????????}
????});
//4、避免alloc产生新对象,所以要重写allocWithZone方法
+(instancetype)allocWithZone:(struct?_NSZone?*)zone{
?if?(stu?==?nil) {
?stu?= [super?allocWithZone:zone];
}
?return?stu;
}
//5、未了避免拷贝产生新对象,我们需要重写copyWithZone以及mutablecopyWithZone方法
-(id)copyWithZone:(NSZone?*)zone{
?return?stu;
}
-(id)mutableCopyWithZone:(NSZone?*)zone{
?return?stu;
}
@end