0

I read in the apple documentation about copyWithZone : "The returned object is implicitly retained by the sender, who is responsible for releasing it". But... How may I release something I return... I'm going crazy !

Sample of code :

    - (id)copyWithZone:(NSZone *)zone {
        MyObject* obj = [[[self class] allocWithZone:zone] init]; // explicit retain
        [obj fillTheObj];

        return obj; // implicit retain
    }

Where should be the told release ? I retain twice ? Uhhh...

Oliver
  • 23,072
  • 33
  • 138
  • 230

1 Answers1

1

The sender is responsible for releasing. That means whoever calls your copy method takes ownership, i.e.:

MyObject *obj = ...
MyObject *aCopy = [obj copy];
... do stuff with aCopy
[aCopy release];
Daniel Dickison
  • 21,832
  • 13
  • 69
  • 89
  • Okkkk, the sender of the call, not the sender of the object. That's more clear. But I'm really going crazy. So... I can pass myObject.var = [localvar copy] with a property in myObject defined as retain, and released in the dealloc. That would work fine, isn't it ? – Oliver Jan 08 '11 at 01:42
  • @Oliver -- you'll be over-retaining if you did that. If the `var` property is declared as `retain`, then the correct assignment would be `myObject.var = [[localvar copy] autorelease]`. But it sounds like what you really want is to declare the property as `copy`, then you can simply do `myObject.var = localvar`. – Daniel Dickison Jan 08 '11 at 20:55