【问题标题】:How to do deep copying Objective-C如何进行深度复制 Objective-C
【发布时间】:2018-10-08 22:52:41
【问题描述】:

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

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

【问题讨论】:

    标签: objective-c copying


    【解决方案1】:

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

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

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

    请注意,您可以通过将属性声明为 copy 来自动执行此操作:

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

    通常将copy 与NSString 和NSArray 一起使用,以防止分配NSMutableString 和NSMutableArray,这可能会在外部被错误地更改。确保在 Symptoms 上实现 NSCopying。

    【讨论】:

      猜你喜欢
      • 2013-12-03
      • 2014-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-13
      • 1970-01-01
      • 1970-01-01
      • 2018-07-30
      相关资源
      最近更新 更多