anotherCoder
anotherCoder

Reputation: 732

Objective C: comparing dictionary contents

I have a dictionary declared, like this,

NSString *responseString = [request responseString];
            responseDict = [responseString JSONValue];
            for (id key in responseDict){
                NSLog(@"%@ : %@", key, [responseDict objectForKey:key]);
            }

Result :

013-01-22 00:14:02.323 PromoTest[2352:c07] A : 0
2013-01-22 00:14:02.325 PromoTest[2352:c07] B : 1
2013-01-22 00:14:02.325 PromoTest[2352:c07] C : 0

now, I want to compare the value and do some operation on it. I presumed the value for a key is of type NSString and compared it to my constant NSString, like this,

NSString *myString1 = @"0";     
NSString *myString2 = [responseDict objectForKey:@"A"];

NSLog(@"%d", (myString1 == myString2)); //1
NSLog(@"%d", [myString1 isEqualToString:myString2]); //1

Result:

2013-01-22 00:19:12.966 PromoTest[2423:c07] 0
2013-01-22 00:19:12.966 PromoTest[2423:c07] 0

Where am i going wrong?? Is my comparison wrong? How do I go about correctly comparing the content??
The data is being received as response data from a web service. I am just converting the data into a dictionary for easily using it. The web service returns a JSON object,

{"A":0,"B":1,"C":0}

Upvotes: 1

Views: 8259

Answers (3)

sash
sash

Reputation: 8725

NSDictionary method isEqualToDictionary can be used to compare 2 dictionaries

Returns a Boolean value that indicates whether the contents of the receiving dictionary are equal to the contents of another given dictionary.

For example:

[myDictionary isEqualToDictionary:expectedDictionary]

Upvotes: 10

vikingosegundo
vikingosegundo

Reputation: 52237

Instead of comparing strings you could also compare number object. here including with a check, if the returned object is a NSNumber, if not, try as string:

if([responseDict[@"A"] isKindOfClass:[NSNumber class]]){
    NSNumber *myNumber1 = @0;     
    NSNumber *myNumber2 = [responseDict objectForKey:@"A"];
    NSLog("Same number: %@",[myNumber1 isEqualToNumber:myNumber2] ? @"YES" : @"NO");

} else if([responseDict[@"A"] isKindOfClass:[NSString class]]){
    NSString *myString1 = @"0";     
    NSString *myString2 = [responseDict objectForKey:@"A"];
    NSLog("Same string: %@",[myString1 isEqualToString:myString2] ? @"YES" : @"NO");
}

Upvotes: 2

Gabriele Petronella
Gabriele Petronella

Reputation: 108169

The only reasonable explanation is that [responseDict objectForKey:@"A"] is not returning a NSString.

You are probably getting a NSNumber back, therefore the comparison fails.

If that's the case you need to get a NSString from the NSNumber before comparing it against your constant. You can do it by

NSString * myString2 = [[responseDict objectForKey:@"A"] stringValue];

Also never use == to compare NSStrings instances. Stick with isEqualToString and you'll be good.

Upvotes: 5

Related Questions