話不多說(shuō),同樣是個(gè)人筆記。
1、在頭文件聲明類(lèi)方法
#import <Foundation/Foundation.h>
@interface Student : NSObject
+ (Student*) getInstance;
@end
2、在源文件中實(shí)現(xiàn)相應(yīng)方法
#import "Student.h"
static Student* instance = nil;
@interface Student()
- (instancetype) init;
@end
@implementation Student
+ (Student*) getInstance {
if (instance == nil) {
instance = [[Student alloc]init];
}
return instance;
}
- (instancetype) init {
return self;
}
//覆蓋allocWithZone
+ (id) allocWithZone:(struct _NSZone *)zone {
@synchronized(self) {
if (!instance) {
instance = [super allocWithZone:zone];//確保使用同一塊內(nèi)存地址
return instance;
}
}
return nil;
}
- (id) copyWithZone: (NSZone*)zone {
return self;//確保copy對(duì)象也是唯一
}
@end
3、調(diào)用
Student* stu1 = [Student getInstance];
Student* stu2 = [Student getInstance];
Student* stu3 = [stu1 copy];
NSLog(@"stu1 = %@", stu1);
NSLog(@"stu2 = %@", stu2);
NSLog(@"stu3 = %@", stu3);
4、測(cè)試結(jié)果
stu1 = <Student: 0x100503920>
stu2 = <Student: 0x100503920>
stu3 = <Student: 0x100503920>