Search code examples
iphonecopyclone

IPhone: Copy/Clone


I want to copy or clone a object of my own written class. But if I call the copy function only the pointer were copied. So if I change the copied object the original object is changed, too.

Is there a way/function to really clone an object?

best regards Melanie


Solution

  • An object can be copied if its class adopts the NSCopying protocol and implements its single method, copyWithZone:.

    See Object copying


    - (id)copyWithZone:(NSZone *)zone{
        MyClass *copy = [[[self class] allocWithZone: zone] init];
        [copy setProperty1:[self property1]];
        return copy;
    }