首页 > 解决方案 > 如何进行深度复制 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 方法中并继续处理当前患者时,在历史上存在指向该对象的链接,该对象具有正确的属性值。一旦我们退出该方法或开始处理另一个患者,所有属性值都会重置为初始值。

我试图实现复制,但还是有问题。

描述患者和症状类别

将对象上的链接添加到历史记录并且对象具有正确值时的情况

当我们从方法 makeNoteIn 出去并且对象在历史数组中具有初始(错误)值时的情况

标签: objective-ccopying

解决方案


当你想深度复制一个对象时,你必须copy在所有子结构上实现:

[newPatient setName:[self.name copy]];
[newPatient setSymptoms:[self.symptoms copy]];

否则,它们仍将引用同一个对象,而更改一个对象将影响所有对象。

请注意,您可以通过将属性声明为copy

@property (copy, nonatomic) NSString *name;
@property (copy, nonatomic) Symptoms *symptoms;

使用copywithNSStringNSArray防止分配是很常见的,NSMutableString并且NSMutableArray可能会在外部被错误地更改。确保您NSCopyingSymptoms.


推荐阅读