1

i'm parsing something from the Apple JSON (the rating of the app) and i tried something like:

 if ([StoreParse objectForKey:@"averageUserRating"] == @"4.5") {
        NSLog(@"xx");
    } else {
        NSLog(@"xxx");
    }

The App has a rating of 4.5 and if i do

NSlog (@"%@", [StoreParse objectForKey:@"averageUserRating"]);

The output is : 4.5

but when i run the script the NSlog in the first code's output is "xxx" does anyone can help me?

Peter Hosey
  • 95,783
  • 15
  • 211
  • 370
Jones
  • 375
  • 7
  • 23

4 Answers4

6

Comparing strings, which are essentially pointers to instances of the NSSring class, is erroneous, as two identical-content strings can have a different memory address. Use

if ([[StoreParse objectForKey:@"averageUserRating"] isEqualToString:@"4.5"])

instead.

4

You can't do this:

if ([StoreParse objectForKey:@"averageUserRating"] == @"4.5")

You need to do:

if ([[StoreParse objectForKey:@"averageUserRating"] isEqualToString:@"4.5"])

That's assuming it's a string. If it's an NSNumber then do:

if ([[StoreParse objectForKey:@"averageUserRating"] floatValue] == 4.5f)

(Although be careful about comparing equality of floats)

See this question for more information on string equality.

Community
  • 1
  • 1
mattjgalloway
  • 34,792
  • 12
  • 100
  • 110
4

Use isEqualToString:

if ([[StoreParse objectForKey:@"averageUserRating"] isEqualToString:@"4.5"]) {
    NSLog(@"xx");
}
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
0

If the value for averageUserRating is an NSNumber, you should convert it to a formatted NSString first then compare it to the @"4.5" string literal:

if ([[NSString stringWithFormat:@"%1.1f", [[StoreParse objectForKey:@"averageUserRating"] floatValue]] isEqualToString:@"4.5"])
cgull
  • 1,407
  • 1
  • 11
  • 18