iphoneautoreleaseretaincountcopywithzone

copyWithZone return value ownership and retain count


I read in the apple documentation about copyWithZone :

"The returned object is implicitly retained by the sender, who is responsible for releasing it".

So if I write this :

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

        return obj;
    }

and I call :

MyStuff* obj = [varobj copy];

will obj be retained? What about the retain count if I don't set autorelease?


Solution

  • Do not autorelease it in your copyWithZone method or you won't own it (and likely won't be able to even do anything with it).

    Remove the autorelease and obj will be appropriately retained in the MyStuff copying. You simply need to release it when you're done with it.

    The Apple sentence is saying that the sender -- which is your MyStuff *obj initialization -- has ownership and needs to release it. "Sender" refers to the object that sent the copy message, not your copyWithZone method.