簡體   English   中英

比較 objective-C 中的 2 個字符串

[英]Compare 2 strings in objective-C

我寫了以下代碼:

   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)時? 請幫忙

當您在像NSString *這樣的指針上使用==時,它是在比較 memory 地址,而不是比較字符串的值。

以下將實際比較字符串值:

if([date isEqualToString:choosedDate])

在 Objective C 比較兩個字符串的更好方法是:

NSString *string1 = <your string>;
NSString *string2 = <your string>;

if ([string1 caseInsensitiveCompare:string2] == NSOrderedSame) {
    //strings are same
} else {
    //strings are not same
}

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

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

我不知道depPricecomPriceprice是否正確分配,也不知道它們的類型是什么,但它們也可能會給您帶來問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM