1

When I assign the value to the bank: banca.name = @"CheBanca!"; the following condition returns true.

if(banca.name==@"CheBanca!"){
        header.bankNameLabel.textColor=[UIColor greenColor];
}

But when I assign the same value as: banca.name = [jsonBanca objectForKey:@"nome_banca"]; the condition return false although NSLog(@"Bank name: %@", [jsonBanca objectForKey:@"nome_banca"]); outputs the value Bank name: CheBanca!

The following code shows how I get jsonBanca:

NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];

NSDictionary *results = [responseString JSONValue];
[responseString release]; 

NSArray *jsonBanche = [results objectForKey:@"banche"];
NSLog(@"%@",jsonBanche);
NSMutableArray  *banks = [NSMutableArray arrayWithCapacity:jsonBanche.count];

for (int i=0; i<jsonBanche.count; ++i) {

        NSDictionary *jsonBanca = [jsonBanche objectAtIndex:i];
}

This code NSLog(@"%@",jsonBanche); returns the banks:

{
    "nome_banca" = "CheBanca!";
    "nome_prodotto" = "Conto Deposito";
    rating = "A-1";
}, ...

The question is why this two strings @"CheBanca!" and the string recieved by JSON are not equal although they contain the same phrase. And how to make them equal to return true in the condition.

Alexey
  • 7,127
  • 9
  • 57
  • 94
  • possible duplicate of [If "a == b" is false when comparing two NSString objects?](http://stackoverflow.com/questions/8598599/if-a-b-is-false-when-comparing-two-nsstring-objects) – mmmmmm Jan 03 '12 at 14:04

3 Answers3

3

To compare strings accurately, you should use the isEqualToString method.

if ([banca.name isEqualToString:@"CheBanca!"]) {
   // strings match
   header.bankNameLabel.textColor=[UIColor greenColor];
}
Manlio
  • 10,768
  • 9
  • 50
  • 79
Bill Burgess
  • 14,054
  • 6
  • 49
  • 86
2

To check for equality between two strings, use isEqualToString:

if ([banca.name isEqualToString:@"CheBanca!"]){
    header.bankNameLabel.textColor = [UIColor greenColor];
}

Your previous code (if (banca.name == @"CheBanca!") {) was only checking for equality of the pointer's address.

Get more details about the NSString class here.

Guillaume
  • 21,685
  • 6
  • 63
  • 95
1

The issue here is that NSString* is a pointer to a NSString, as they are loaded through separate ways they are two different NSStrings and have two different addresses. == compares the addresses and so sees them as different.

To compare the values of the string use the compare: and related methods of NSString or the isEqualToString: method

Manlio
  • 10,768
  • 9
  • 50
  • 79
mmmmmm
  • 32,227
  • 27
  • 88
  • 117