【问题标题】:How to compare NSString value with NSMutableDictionary key in iPhone?如何将 NSString 值与 iPhone 中的 NSMutableDictionary 键进行比较?
【发布时间】:2013-06-15 05:46:27
【问题描述】:

我是开发新手。我不明白为什么它不工作我的代码在下面

if(selectAnswer == [[self.testQuesArray objectAtIndex:0]objectForKey:@"correct_answer"]
{
    NSLog(@"Correct Answer");
}

其中 selectAnswer 是 NSString,而 correct_answer 是“键”,0 是它的“值”。请告诉我解决方案为什么它没有出现在“If”正文中?

【问题讨论】:

  • 使用isEqualToString: 方法代替== ...!!

标签: iphone ios objective-c nsstring nsmutabledictionary


【解决方案1】:

您正在比较字符串,因此您必须使用 isEqualToString 代替“==”。

if([selectAnswer isEqualToString : [NSString stringWithFormat:@"%@",[[self.testQuesArray objectAtIndex:0]objectForKey:@"correct_answer"]]]
{
NSLog(@"Correct Answer");
}

希望这对你有帮助。

【讨论】:

    【解决方案2】:

    试试这个代码:

     if ([selectAnswer isEqualToString:[NSString stringWithFormat:@"%@",[[self.testQuesArray objectAtIndex:0]objectForKey:@"correct_answer"]]]) 
       {
    
       }
    

    【讨论】:

    • 使用文字。 [self.testQuesArray[0][@"correct_answer"] stringValue] 就够了
    • 为什么是`stringWithFormat:@"%@"'?完全是多余的。
    【解决方案3】:

    实际上现在你是comparing 两个pointers(address of string) 而不是两个strings。所以使用不同朋友提供的ans Like:

    if([selectAnswer isEqualToString : [self.testQuesArray[0][@"correct_answer"] stringValue])
    

    if([selectAnswer isEqualToString : [NSString stringWithFormat:@"%@",[[self.testQuesArray objectAtIndex:0]objectForKey:@"correct_answer"]]]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多