0

I have below code

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");
}

Output I am getting is

do not lock the app
do not lock the app

However when I use actual values for firstName & secondName, I get output as

lock the app
do not lock the app

Below are details of 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];
}

If I print firstName & secondName, I get values as 1.6.1, 1.6.1 respectively.

Any idea why there are two different outputs when using equals?

user2864740
  • 60,010
  • 15
  • 145
  • 220
Fahim Parkar
  • 30,974
  • 45
  • 160
  • 276

1 Answers1

3

You will get different behaviour for == and isEqualToString:. Because == operator compares only the address of object and isEqualToString: will compare string value.

You should not use == for string comparison.

kkumpavat
  • 452
  • 2
  • 10
  • I do understand that, but why for the first code it works? where I am assigning values manually? – Fahim Parkar Jun 09 '14 at 06:56
  • 4
    Constant string literals (like `@"1.6"`) are given the same memory address by the compiler, when you use them more than once. – jrturton Jun 09 '14 at 06:57
  • Yes, constants string are handled in different ways, If you use constant at ore then one place, all will have same address as compiler have given them same memory address. – kkumpavat Jun 09 '14 at 07:15