1

我有一本声明的字典,像这样,

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

结果 :

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

现在,我想比较该值并对其进行一些操作。我假设键的值是 NSString 类型,并将其与我的常量 NSString 进行比较,如下所示,

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

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

结果:

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

我哪里错了??我的比较有错吗?如何正确比较内容?
数据作为响应数据从 Web 服务接收。我只是将数据转换成字典以便于使用它。Web 服务返回一个 JSON 对象,

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

3 回答 3

10

NSDictionary方法isEqualToDictionary可用于比较两个字典

返回一个布尔值,指示接收字典的内容是否等于另一个给定字典的内容。

例如:

[myDictionary isEqualToDictionary:expectedDictionary]
于 2014-12-17T15:24:22.697 回答
5

唯一合理的解释是[responseDict objectForKey:@"A"]不返回NSString.

您可能会得到NSNumber回报,因此比较失败。

如果是这种情况,您需要先从 中获取 a NSStringNSNumber然后再将其与常量进行比较。你可以这样做

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

也永远不要==用来比较NSStrings 实例。坚持下去isEqualToString,你会很好的。

于 2013-01-21T18:59:00.747 回答
2

除了比较字符串,您还可以比较数字对象。这里包括检查,如果返回的对象是 NSNumber,如果不是,请尝试作为字符串:

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");
}
于 2013-01-21T19:08:58.303 回答