objective-c - 如何进行深度复制 Objective-C
问题描述
有一个类 Patient 具有以下属性:
@property (strong, nonatomic) NSString *name;
@property (strong, nonatomic) Symptoms *symptoms;
@property (assign, nonatomic) Status status;
@property (weak, nonatomic) id <PatientDelegate> delegate;
有一个具有属性的类症状:
@property (assign, nonatomic) CGFloat temperature;
@property (assign, nonatomic) BOOL headache;
@property (assign, nonatomic) BOOL stomach_ache;
这两个类都实现了协议 NSCopying:
- (nonnull id)copyWithZone:(nullable NSZone *)zone {
Patient *newPatient = [[[self class] allocWithZone:zone] init];
[newPatient setName:self.name];
[newPatient setSymptoms:self.symptoms];
[newPatient setStatus:self.status];
[newPatient setDelegate:self.delegate];
return newPatient;
}
- (nonnull id)copyWithZone:(nullable NSZone *)zone {
Symptoms *newSymptoms = [[[self class] allocWithZone:zone] init];
[newSymptoms setTemperature:self.temperature];
[newSymptoms setHeadache:self.headache];
[newSymptoms setStomach_ache:self.stomach_ache];
return newSymptoms;
}
还有一个类Doctor:
@property (strong, nonatomic) NSString *name;
@property (strong, nonatomic) NSMutableArray *history;
- (void)makeNoteIn:(Patient *)patient card:(NSMutableArray *)history;
- (void)report;
当病人好转时,医生调用方法 makeNoteIn:
- (void)makeNoteIn:(Patient *)patient card:(NSMutableArray *)history {
Patient *newRecord = [patient copy];
[history addObject:newRecord];
}
记录完成后,患者所有财产恢复原值。当我们在 makeNoteIn 方法中并继续处理当前患者时,在历史上存在指向该对象的链接,该对象具有正确的属性值。一旦我们退出该方法或开始处理另一个患者,所有属性值都会重置为初始值。
我试图实现复制,但还是有问题。
解决方案
当你想深度复制一个对象时,你必须copy
在所有子结构上实现:
[newPatient setName:[self.name copy]];
[newPatient setSymptoms:[self.symptoms copy]];
否则,它们仍将引用同一个对象,而更改一个对象将影响所有对象。
请注意,您可以通过将属性声明为copy
:
@property (copy, nonatomic) NSString *name;
@property (copy, nonatomic) Symptoms *symptoms;
使用copy
withNSString
和NSArray
防止分配是很常见的,NSMutableString
并且NSMutableArray
可能会在外部被错误地更改。确保您NSCopying
在Symptoms
.
推荐阅读
- mysql - 返回错误但完成插入的 SQLSTATE
- css - Grid Gap Boostrap - 如何修复?
- python - Keras 的准确率低于任何分类器
- java - 将文件输入 Java 以生成新的输出文件
- jquery - 选择一个 Jquery UI 工具提示动画
- python - 布尔条件为 True,但 while 循环仍未中断
- javascript - 将点击侦听器添加到 vue 中的列表元素的问题
- sql-server - 使用 Tableau 创建仪表板的 Hive 性能?
- angular - Auth Guard 在无效 url 的情况下导航到基本 url
- php - PHP in_array 与正则表达式干草堆数组