Note that there are some explanatory texts on larger screens.

plurals
  1. POObjectiveC - Releasing objects added as parameters
    primarykey
    data
    text
    <p>Ok, here goes.</p> <p>Being a Java developer I'm still struggling with the memory management in ObjectiveC. I have all the basics covered, but once in a while I encounter a challenge.</p> <p>What I want to do is something which in Java would look like this:</p> <pre><code>MyObject myObject = new MyObject(new MyParameterObject()); </code></pre> <p>The constructor of <code>MyObject</code> class takes a parameter of type <code>MyParameterObject</code> which I initiate on-the-fly.</p> <p>In ObjectiveC I tried to do this using following code:</p> <pre><code>MyObject *myObject = [[MyObject alloc] init:[[MyParameterObject alloc] init]]; </code></pre> <p>However, running the Build and Analyze tool this gives me a "Potential leak of an object" warning for the <code>MyParameter</code> object which indeed occurs when I test it using Instruments. I do understand why this happens since I am taking ownership of the object with the <code>alloc</code> method and not relinquishing it, I just don't know the correct way of doing it. I tried using</p> <pre><code>MyObject *myObject = [[MyObject alloc] init:[[[MyParameterObject alloc] init] autorelease]]; </code></pre> <p>but then the Analyze tool told me that "Object sent -autorelease too many times".</p> <p>I could solve the issue by modifying the <code>init</code> method of <code>MyParameterObject</code> to say <code>return [self autorelease];</code> in stead of just <code>return self;</code>. Analyze still warnes about a potential leak, but it doesn't actually occur. However I believe that this approach violates the convention for managing memory in ObjectiveC and I really want to do it the right way.</p> <p>Thanx in advance.</p>
    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.
    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