OC--单例模式
2016-02-25 本文已影响50人
就怕是个demo
话不多说,同样是个人笔记。
1、在头文件声明类方法
#import <Foundation/Foundation.h>
@interface Student : NSObject
+ (Student*) getInstance;
@end
2、在源文件中实现相应方法
#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];//确保使用同一块内存地址
return instance;
}
}
return nil;
}
- (id) copyWithZone: (NSZone*)zone {
return self;//确保copy对象也是唯一
}
@end
3、调用
Student* stu1 = [Student getInstance];
Student* stu2 = [Student getInstance];
Student* stu3 = [stu1 copy];
NSLog(@"stu1 = %@", stu1);
NSLog(@"stu2 = %@", stu2);
NSLog(@"stu3 = %@", stu3);
4、测试结果
stu1 = <Student: 0x100503920>
stu2 = <Student: 0x100503920>
stu3 = <Student: 0x100503920>