我有下面的代码
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.1
,1.6.1
分别。
知道为什么使用equals时会有两个不同的输出吗?
你会得到不同的行为==
和isEqualToString:
。因为==
运算符仅比较对象的地址,并且isEqualToString:
将比较字符串值。
您不应该将其==
用于字符串比较。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句