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

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

    Following the explanation at http://www.techotopia.com/index.php/Copying_Objects_in_Objective-C

    "This can be achieved by writing the object and its constituent elements to an archive and then reading back into the new object."

    @implementation ClassA
    
    - (id)copyWithZone:(NSZone*)zone{
        NSData *buffer;
        buffer = [NSKeyedArchiver archivedDataWithRootObject:self];
        ClassA *copy = [NSKeyedUnarchiver unarchiveObjectWithData: buffer];
        return copy;
    }
    @end
    

提交回复
热议问题