tags:

views:

45

answers:

1

I feel embarrassed asking this, but it seems like something I need to understand:

Why does this evaluate to true? (if I cast it to int it properly evaluates to false)

NSString *var1 = @"ABC";
NSString *var2 = @"ABCD";

if (([var1 length] - [var2 length]) > 2) NSLog(@"-1 > 2");
+6  A: 

length is unsigned.

See docs:

length
Returns the number of Unicode characters in the receiver.

- (NSUInteger)length

Return Value
The number of Unicode characters in the receiver.
Michael Krelin - hacker
Try: if (((int)[var1 length] - (int)[var2 length]) > 2) NSLog(@"-1 > 2");
Rob
Or `if ([var1 length] > (2 + [var2 length]))` to avoid the subtraction. Look ma! I used algebra in the real world! (Of course, theoretically, you'd have to deal with overflow, but not realistically.)
kperryua