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