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

前端 未结 6 1688
爱一瞬间的悲伤
爱一瞬间的悲伤 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:56

    Objective-C on iOS doesn’t offer any direct language or library construct to switch between a shallow and a deep copy. Each class defines what it means to “get its copy”:

    @implementation ClassA
    
    - (id) copyWithZone: (NSZone*) zone
    {
        ClassA *copy = [super copyWithZone:zone];
        [copy setBClass:bClass]; // this would be a shallow copy
        [copy setBClass:[bClass copy]]; // this would be a deep copy
        return copy;
    }
    
    @end
    

    Of course you would have to do the same decision in ClassB and ClassC. If I am not mistaken, the usual semantics for a copy in Objective-C is to return a shallow copy. See also this question about copying arrays for more discussion of the topic.

提交回复
热议问题