Comparing NSDecimalNumbers in Objective-C

​So ran into this issue when checking if an NSDecimalNumber variable is less than zero:

if(myNSDecimalNumberVariable < 0)
{
       <the then code block>
}
else
{
       <the else code block>
}

and it was always going to the else, regardless of the value of my variable.

Apparently what is happening is that pointer addresses are being compared. If I was comparing two NSDecimalNumbers I would have similar "strange" behaviour. I'm guessing to someone who grew up on a language familiar with pointers, that this would have been obvious. However, I was not that fortunate.

The correct way to do a comparison is to use the "compare" instance method:
if([myNSDecimalNumberVariable compare:[NSDecimalNumber zero]] == NSOrderedDescending)
....<the rest of if statement>

This is something to keep in mind with a lot of the Objective-C types.

Dave at innerexception showed me the light...

Comments