title: Dynamic typing and return values in Objective-C
body: <p>I have run into a very strange behaviour I can’t make sense of. I have a <code>Texture</code> class with <code>contentWidth</code> property of type <code>int</code>. This class is wrapped in a <code>Image</code> class that has a <code>width</code> property of type <code>int</code>. The <code>width</code> of an <code>Image</code> is computed simply as the <code>contentWidth</code> of the underlying texture:</p>
  
  <pre><code>- (int) width
  {
      return texture.contentWidth;
  }
  </code></pre>
  
  <p>Now the <code>Image</code> is used by a <code>Button</code> class (by composition, not inheritance) that wants to read the image size:</p>
  
  <pre><code>// image is of type ‘id’
  int width = [image width];
  int height = [image height];
  </code></pre>
  
  <p>The problem is that the <code>height</code> variable gets set just fine, whereas the <code>width</code> variable contains <code>NaN</code> (–2147483648). I have checked the dimensions – they are about 200×100 or so, nowhere near the <code>int</code> limit. Also the Xcode debugger tooltip shows both properties in the <code>Texture</code> correctly, only after the width gets through the two accessors the number gets garbled. The objects are not freed. What am I missing?</p>
  
  <hr>
  
  <p><em>Update:</em> I have expanded the accessor in the <code>Image</code> class to see where the problem originates:</p>
  
  <pre><code>- (int) width
  {
      const int w = texture.contentWidth;
      return w;
  }
  </code></pre>
  
  <p>Now when I break on the first line, the <code>w</code> gets set correctly. I step over, the execution returns to the calling function:</p>
  
  <pre><code>- (void) foo
  {
      int bar = [image width];
  }
  </code></pre>
  
  <p>…and now the <code>bar</code> contains <code>NaN</code>.</p>
  
  <hr>
  
  <p><em>Update:</em> Mhm, got it:</p>
  
  <pre><code>int foo = [image width]; // image is id, returns NaN
  int bar = [(Image*) image width]; // correct value
  </code></pre>
  
  <p>The <code>image</code> is declared as <code>id</code>, which is the point here. Could somebody explain this? I have got a feeling I am not calling the right <code>width</code> method, but what exactly is going on here? I always type my variables as strictly as possible, but here the <code>id</code> type is handy. I had no idea it could result in such a bug.</p>