Q:NSString length负数比较问题

来源:互联网 发布:安卓编程软件手机软件 编辑:程序博客网 时间:2024/06/18 18:30

- (void) testStringLength {    NSString * str = @"1111111111";    NSLog(@"%d", -str.length);    if (-str.length > 801) {        NSLog(@"wrong");    } else {        NSLog(@"right");    }} 

LOG

2013-02-20 18:54:17.900 test[21134:f803] -102013-02-20 18:54:25.235 test[21134:f803] wrong

这是肿么回事?

解析:

- (void) testStringLength {    NSString * str = @"1111111111";    NSLog(@"%d", -str.length);    long long temp = LONG_LONG_MAX;    while (-str.length < temp) {        temp /= 10;        NSLog(@"%lld", temp);    }        temp *= 10;    while (-str.length < temp) {        temp /= 2;        NSLog(@"%lld", temp);    }        temp *= 2;    while (-str.length < temp) {        temp -= temp / 3;        NSLog(@"%lld", temp);    }        if (-str.length < temp) {        NSLog(@"wrong");    } else {        NSLog(@"right");    }} 

LOG:

2013-02-21 11:50:01.190 test[2183:f803] -102013-02-21 11:50:01.195 test[2183:f803] 9223372036854775802013-02-21 11:50:01.195 test[2183:f803] 922337203685477582013-02-21 11:50:01.195 test[2183:f803] 92233720368547752013-02-21 11:50:01.196 test[2183:f803] 9223372036854772013-02-21 11:50:01.196 test[2183:f803] 922337203685472013-02-21 11:50:01.197 test[2183:f803] 92233720368542013-02-21 11:50:01.197 test[2183:f803] 9223372036852013-02-21 11:50:01.197 test[2183:f803] 922337203682013-02-21 11:50:01.198 test[2183:f803] 92233720362013-02-21 11:50:01.198 test[2183:f803] 9223372032013-02-21 11:50:01.198 test[2183:f803] 46116860152013-02-21 11:50:01.199 test[2183:f803] 23058430072013-02-21 11:50:01.199 test[2183:f803] 3074457343

分析:

-str.length 大小应该在最后2个数之间,比LONG_MAX:2147483647大一些

- (NSUInteger)length;

length返回是一个无符号的int,-str.length貌似强行转换成了NSUInteger



原创粉丝点击