單例使用方法
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