How can I make a deep copy in Objective-C?

前端 未结 6 1678
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-05 14:03

I\'m learning ios development and I\'m confused with deep copying in Objective-C. For example,I have three class below. Now I want to deep copy ClassA, can anybody teach me

6条回答
  •  粉色の甜心
    2020-12-05 14:55

    You should add the copyWithZone: method in each class you want to be copiable.

    NB: I wrote this by hand, watch out for typos.

    -(id) copyWithZone:(NSZone *) zone
    {
        ClassA *object = [super copyWithZone:zone];
        object.aInt = self.aInt;
        object.bClass = [self.bClass copyWithZone:zone];
        return object;
    }
    
    -(id) copyWithZone:(NSZone *) zone
    {
        ClassB *object = [super copyWithZone:zone];
        object.bInt = self.bInt;
        object.cClass = [self.cClass copyWithZone:zone];
        return object;
    }
    
    -(id) copyWithZone:(NSZone *) zone
    {
        ClassC *object = [super copyWithZone:zone];
        object.cInt = self.cInt;
        object.str = [self.str copy];
        return object;
    }
    

提交回复
热议问题