iOS Quick Tips: Why can’t I compare two numbers?!?

Recently, I was trying to debug some code that wasn’t working properly. The code looked something like this:

if(someNumber > 0)
{
   // Do some really important stuff
}

… but even when someNumber was supposed to be 0, the block was always being entered. What the heck? I can’t even compare two numbers properly? I smacked my forehead when I realized that someNumber was actually a NSNumber*, not an int, and what I really wanted to do was this:

if(someNumber.intValue > 0)
{
   // Do some really important stuff
}

Of course, this wasn’t flagged as a warning by the compiler, because as is typical with the C family of languages, checking if a pointer (or an id) is greater than 0 is a perfectly valid operation.

I guess the moral of the story is that if some basic operation isn’t working, take a step back and make sure that your initial assumptions are valid!

Leave a Reply

Your email address will not be published. Required fields are marked *