Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy in Objective-C does doing alloc and init in separate statements cause the object to be released according to the Xcode static analyzer?
    text
    copied!<p>I'm making my first steps with Objective-C and have encountered a minor, albeit confusing issue with the static analyzer (Product->Analyze) in XCode 4.1. I have created a simple Fraction class for rational numbers which I allocate and initialize like this,</p> <pre><code>Fraction* f = [[[ Fraction alloc ] initWithNumerator:3 withDenomimator:5] autorelease]; [ f print ]; </code></pre> <p>where <code>print</code> is a method which just uses <code>NSLog</code> to display the fraction, everything works fine. However, if I split the <code>alloc</code>/<code>init</code> construct apart into two statements (I realize this is non-idiomatic - I'm just trying to understand the machinery) and use manual <code>release</code> rather than <code>autorelease</code> giving:</p> <pre><code>Fraction* f = [ Fraction alloc ]; // 1. Method returns an Objective-C object with // a +1 retain count (owning reference) [ f initWithNumerator:3 withDenomimator:5]; // 2. Object released [ f print ]; // 3. Reference-counted object is used after it is released [ f release ]; </code></pre> <p>the program still appears to run without error, but the XCode analyzer gives the warnings in the comments. Why does XCode think the <code>init</code> call causes the object to be released?</p> <p>Thinking through this further as I frame the question I can see that my two programs are not quite equivalent because in the first snippet my pointer <code>f</code> is the result of the call to <code>init</code> whereas in the second snippet it is the result of <code>alloc</code>. So changing my code to,</p> <pre><code> Fraction* a = [ Fraction alloc ]; Fraction* f = [ a initWithNumerator:3 withDenomimator:5]; [ f print ]; [ f release ]; // or should it be [ a release ] ? </code></pre> <p>makes it exactly equivalent and the static analyzer stops complaining. So is it possible that <code>init</code> can return a different pointer than the one passed to it from <code>alloc</code>, rather than just <em>configuring</em> the memory it has been passed? With this code should I pair <code>[ a release ]</code> with the <code>alloc</code> or <code>[ f release ]</code> with the <code>init</code>?</p>
 

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