views:

40

answers:

3

Here is the code:

- (id)copyWithZone:(NSZone*)zone {
    ExecutedOrderInfo* copy = [[self class] allocWithZone:zone];
    copy.executedPrice = self.executedPrice;
    copy.executedQuantity = self.executedQuantity;
    return (id)copy;
}

The question is, is it necessary to release "copy" in above code? Or release it when someone called it?

A: 

If I'm reading your code correctly - No. The method doesn't create the object so it doesn't need to release it.

Derek Clarkson
ExecutedOrderInfo* copy = [[self class] allocWithZone:zone]you see this?
the `allocWithZone:` method actually is a object creation.
Max Seelemann
Doh! Was reading that as a factory method, not a create. Yep your right. This needs an init.
Derek Clarkson
+3  A: 

No, not in this method. Methods that start with copy must return non-autorleased objects with retain count 1. Just as you do.

PS: the cast in return (id)copy is not needed. id is the abstract object type and much more general than your concrete class. Casts are only needed when having a concrete class that should be treated as a different one -- like a subclass after doing a subclass check.

PPS: Your method lacks an init. It's not good to just alloc a instance. Instead do something like this: [[[self class] allocWithZone:zone] init];

Max Seelemann
thanks Max, this helps a lot to me. and also thank you for using simple English..
A: 

Max is right. But all design and intend depend on you. (Even if generally copyXXX means return non-autoreleased object)

And to prevent memory leaks, use Statics Analysis and Instruments after using it.

alones