Two kinds of bug may happen in ios comparison operation:
1. compare NSNumber to integer
NSNumber cannot be used to compare with an integer directly using == operator, as
NSNumber num=...;
if (num == 0){
}
will fail, as == in objective c will compare two objects are refer to the same one, instead [NSNumber isEquelToNumber:] should be used to compare NSNumber. However, the below code still does not work
NSNumber* num =...;
if ([num isEqualToNumber: 0]){
...
}
as isEqualToNumber requires the input parameter also a NSNumber object, passing a integer will throw exception.
So the correct comparison with integer should be
if (num.intValue ==0){
}
assume num is not nil.
2. condition operation
NSString a = "a";
NSString b= "";
NSString c="c";
NSString d="d";
NSString c= a+b?c:d;
The expected result is "ad", however, the actual result is "ac", as + has priority over :, so the above expression is equal to (a+b)?c:d, as a+b is always true, so c is used instead of d.
The fix is explicitly set the priority as a+ (b?c:d), which will generate the result of "ad";
1. compare NSNumber to integer
NSNumber cannot be used to compare with an integer directly using == operator, as
NSNumber num=...;
if (num == 0){
}
will fail, as == in objective c will compare two objects are refer to the same one, instead [NSNumber isEquelToNumber:] should be used to compare NSNumber. However, the below code still does not work
NSNumber* num =...;
if ([num isEqualToNumber: 0]){
...
}
as isEqualToNumber requires the input parameter also a NSNumber object, passing a integer will throw exception.
So the correct comparison with integer should be
if (num.intValue ==0){
}
assume num is not nil.
2. condition operation
NSString a = "a";
NSString b= "";
NSString c="c";
NSString d="d";
NSString c= a+b?c:d;
The expected result is "ad", however, the actual result is "ac", as + has priority over :, so the above expression is equal to (a+b)?c:d, as a+b is always true, so c is used instead of d.
The fix is explicitly set the priority as a+ (b?c:d), which will generate the result of "ad";