Note that there are some explanatory texts on larger screens.

plurals
  1. POObjective-C Returning Autoreleased Copies
    primarykey
    data
    text
    <p>A strange issue I've come across trying to understand Apple's Memory Management standards. Lets say I have a method that returns a copy without letting the user know that it is a copy.</p> <pre><code>+(Point2D*) Add:(Point2D*)a To:(Point2D*)b { Point2D * newPoint = [a copy]; [newPoint Add:b]; // Actually perform the arithmetic. return [newPoint autorelease]; } </code></pre> <p>The problem is that Xcode's Analyze function flags this as an object being sent too many -autorelease calls. I'm assuming this is because -copy implicitly assumes that you are taking ownership, and thus the possibility of +0 retain count is likely. But I'm not entirely sure.</p> <p>Xcode's Analyze Information</p> <pre><code>+(Point2D*) Add:(Point2D*)a To:(Point2D*)b { Point2D * newPoint = [a copy]; // &lt;- 1. Method returns an Objective-C object with a +0 retain count. [newPoint Add:b]; return [newPoint autorelease]; // &lt;- 2. Object sent -autorelease method. // &lt;- 3. Object returned to caller with a +0 retain count. // &lt;- 4. Object over -autoreleased: object was sent -autorelease but the object has zero (locally visible) retain counts. } </code></pre> <p>Any tips or hints on why this is happening? Unless I'm missing something, the code should work fine because the autorelease wont trigger until a safe time (i.e. it works kind of like a convenience constructor, user has time to retain.)</p> <p>As per request, -copyWithZone: would be implemented as such:</p> <pre><code>-(id)copyWithZone:(NSZone *)zone { return [[Point2D allocWithZone:zone] initX:x Y:y Z:z]; } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload