==和isEqualToString给出了奇怪的行为

时间:2014-06-09 06:52:19

标签: objective-c nsstring equals

我有以下代码

NSString *firstName = @"1.6.1";
NSString *secondName = @"1.6.1";

if (!(firstName==secondName)) {
    NSLog(@"lock the app");
} else {
    NSLog(@"do not lock the app");
}

if (!([firstName isEqualToString:secondName])) {
    NSLog(@"lock the app");
} else {
    NSLog(@"do not lock the app");
}

我得到的输出是

do not lock the app
do not lock the app

但是当我使用firstName&的实际值时secondName,我的输出为

lock the app
do not lock the app

以下是firstName& secondName

 // this is coming from server
 firstName = [[NSUserDefaults standardUserDefaults] stringForKey:@"iPhoneAppVersion"];

 // this is coming from app version from iPhone
 secondName = [self appNameAndVersionNumberDisplayString];

- (NSString *)appNameAndVersionNumberDisplayString {
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *appDisplayName = [infoDictionary objectForKey:@"CFBundleDisplayName"];
    NSString *majorVersion = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    NSString *minorVersion = [infoDictionary objectForKey:@"CFBundleVersion"];

    return [NSString stringWithFormat:@"%@",
            minorVersion];
}

如果我打印firstName& secondName,我的值分别为1.6.11.6.1

在使用equals时,知道为什么有两个不同的输出?

1 个答案:

答案 0 :(得分:3)

==isEqualToString:会有不同的行为。因为==运算符仅比较对象的地址,而isEqualToString:将比较字符串值。

您不应使用==进行字符串比较。