Implicit Use of String Length in Objective-C as Boolean Value Is Dangerous

In addition to the previous post, I found that implicitly use of string length as boolean is un-reliable.

Try this.

1
2
3
4
5
6
BOOL ugly = [trimmedString length];
BOOL beauty = [trimmedString length] > 0;

BOOL p1 = ugly == beauty;
BOOL p2 = [trimmedString length] == ([trimmedString length] > 0);
BOOL p3 = ((BOOL)[trimmedString length]) == ([trimmedString length] > 0);

If you print out the value of each statement above, you will get

1
2
3
4
5
6
YES
YES

NO
NO
NO

Comments