2

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

DeFlo
  • 141
  • 1
  • 1
  • 9

2 Answers2

2

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;
}
beryllium
  • 29,669
  • 15
  • 106
  • 125
  • 1
    I already read this. But I dont really understand what zone is? "The zone identifies an area of memory from which to allocate for the new instance. If zone is NULL, the new instance is allocated from the default zone, which is returned from the function NSDefaultMallocZone." So what do I have to write for Zone? – DeFlo Jan 16 '12 at 10:57
  • @MeMa, nice comment. I think you don't need to worry about NSZone, just use default zone. NSZone allow to store information for allocation, handling and freeing objects. – beryllium Jan 16 '12 at 11:19
1

What you are after is refered to as Deep Copy, where you want to copy the contents of a pointer, not the address it points to.

There are a few stack overflow questions about this list Below:

Additionally here is a article from Techtopia: Here

Addition here is my Google Search: Here

Community
  • 1
  • 1
CStreel
  • 2,642
  • 2
  • 19
  • 37