单例使用方法

作者 : 开心源码 本文共818个字,预计阅读时间需要3分钟 发布时间: 2022-05-12 共170人阅读

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

说明
1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是摆设,本站源码仅提供给会员学习使用!
7. 如遇到加密压缩包,请使用360解压,如遇到无法解压的请联系管理员
开心源码网 » 单例使用方法

发表回复