【问题标题】:Compare 2 strings in objective-C比较objective-C中的2个字符串
【发布时间】:2011-05-25 01:19:59
【问题描述】:

我写了以下代码:

   if (depSelectedIndice > -1 && comSelectedIndice> -1)
        {
            NSLog(@"depart elemet : %d ",depSelectedIndice);
            NSLog(@"depart elemet : %d ",comSelectedIndice);
            NSLog(@"ok1");
            NSString *choosedDate =[NSString stringWithFormat:@"%@%@",[deparatureDates objectAtIndex:depSelecif (depSelectedIndice > -1 && comSelectedIndice> -1)
    {
        NSLog(@"depart elemet : %d ",depSelectedIndice);
        NSLog(@"depart elemet : %d ",comSelectedIndice);
        NSLog(@"ok1");
        NSString *choosedDate =[NSString stringWithFormat:@"%@%@",[deparatureDates objectAtIndex:depSelectedIndice], [goingBackDates objectAtIndex:comSelectedIndice]];
        NSLog(@"0000000000001");

        NSLog(@" number of element : %d", [allCombinations count]);
//        for (int j=0; j<[allCombinations count]; j++)
//        {
//            NSLog(@"111111111111111111");
//           // NSString *date = [[allCombinations objectAtIndex:j] objectForKey:@"keydate"];
//            NSLog(@"22222222222222222222");
//              if([date isEqualToString:choosedDate])
//              {
//                  depPrice.text=@"1";
//                  comPrice.text=@"1";
//                  price.text=@"3";
//                  
//              }
       // }
    }

allCombinations 是在.h 中声明的NSArray,我有 initilase 并在另一种方法中使用它。我不能在这种方法中使用? :/

但是我发生了崩溃。我真的不知道问题出在哪里,但我认为是当我比较if(date==choosedDate) 时?请帮忙

【问题讨论】:

  • 当崩溃发生时你能添加你的堆栈跟踪吗?
  • @dredful @dredful @Chris 谢谢大家。我编辑了我的帖子。问题来自 allCombinations 。我在控制台中有 0000000000001。当我使 [allCombinations count] 时出现问题。控制台中没有错误将其发布到此处:( 请帮助
  • "allCombinations 是在 .h 中声明的 NSArray,我有 initilase 并在另一种方法中使用它。我不能在这种方法中使用?:/" - 你必须向我们展示代码/methods 与 allCombinations 相关,因此我们可以查看您是否使用它做错了什么。

标签: objective-c iphone string nsstring comparison


【解决方案1】:

当您在像 NSString * 这样的指针上使用 == 时,它是在比较内存地址,而不是比较字符串的值。

下面会实际比较字符串值:

if([date isEqualToString:choosedDate])

【讨论】:

    【解决方案2】:

    在 Objective C 中比较两个字符串的更好方法是:

    NSString *string1 = <your string>;
    NSString *string2 = <your string>;
    
    if ([string1 caseInsensitiveCompare:string2] == NSOrderedSame) {
        //strings are same
    } else {
        //strings are not same
    }
    

    【讨论】:

      【解决方案3】:

      除了使用[date isEqualToString:choosedDate] 而不是date==choosedDate,我最初的反应是确保depSelectedIndicecomSelectedIndice 不引用deparatureDatesgoingBackDates 末尾之后的元素下一行。

      NSString *choosedDate =[NSString stringWithFormat:@"%@%@",[deparatureDates objectAtIndex:depSelectedIndice], [goingBackDates objectAtIndex:comSelectedIndice]];
      

      我不知道 depPricecomPriceprice 是否被正确分配,也不知道它们的类型是什么,但它们也可能会给您带来问题。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-02-05
        • 2019-11-10
        • 1970-01-01
        • 1970-01-01
        • 2010-10-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多