Wednesday, April 27, 2011

Comparing Variables

I have seen quite a lot of people asking some basic questions about comparing integers, floats, strings, and so on. Many made mistakes in doing so. Such mistakes are:

float x = 0.1;

if (x==0.1) {

// do something

}

This won't work, because a float is what it is.. a number that "floats". A 0.1 is not precisely a 0.1.  In the case of above, x being set to 0.1, but it may hold a value of 0.1000000001 or -0.100000002341 and so on.

So the correct way to compare a float is to set a range.
float x = 0.1;

if ((x<=0.10005)&&(x>=0.00005)) {

// do something

}

There is another variable comparison mistakes that people often do, and asked why it does not work and that is comparing NSString.

NSString *myStr = @"My House";

if (result==myStr) {

// do something

}

This, too, will not work because an NSString is a pointer. A pointer is like an address to your home. Your house needs a renovation, but you are trying to renovate the address. Which is absurd.

There are often a simple function to compare string objects, an in XCode, it is called isEqualToString:

Thus, the correct way to do it is:
NSString *myStr = @"My House";

if ([result isEqualToString:myStr]) {

// do something

}

You can interchange result and myStr in that syntax, no problem. I hope this simple tutorial post helps noobies to understand the variables and how to compare them the correct way. As this tutorial is a simple one, there are no downloadable source codes.

No comments:

Post a Comment