[英]Compare 2 strings in objective-C
I wrote the following code:我写了以下代码:
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 is an NSArray
declared in.h, I have initilase and used it in another method. allCombinations 是在.h 中声明的
NSArray
,我有 initilase 并在另一种方法中使用它。 I can't use in in this method?我不能在这种方法中使用? :/
:/
But I have a crash.但我有一个崩溃。 I don't really know where the problem is but I think it's when I compare
if(date==choosedDate)
?我真的不知道问题出在哪里,但我认为是在比较
if(date==choosedDate)
时? Help please请帮忙
When you use an ==
on pointers like NSString *
it is comparing memory addresses, not comparing the value of strings.当您在像
NSString *
这样的指针上使用==
时,它是在比较 memory 地址,而不是比较字符串的值。
The following will actually compare the string values:以下将实际比较字符串值:
if([date isEqualToString:choosedDate])
In Objective C better way to compare two string is:在 Objective C 比较两个字符串的更好方法是:
NSString *string1 = <your string>;
NSString *string2 = <your string>;
if ([string1 caseInsensitiveCompare:string2] == NSOrderedSame) {
//strings are same
} else {
//strings are not same
}
In addition to using [date isEqualToString:choosedDate]
instead of date==choosedDate
, my initial reaction would be to make sure that depSelectedIndice
and comSelectedIndice
do not refer to elements past the end of deparatureDates
and goingBackDates
in the following line.除了使用
[date isEqualToString:choosedDate]
而不是date==choosedDate
,我最初的反应是确保depSelectedIndice
和comSelectedIndice
不会引用下一行中deparatureDates
和goingBackDates
末尾的元素。
NSString *choosedDate =[NSString stringWithFormat:@"%@%@",[deparatureDates objectAtIndex:depSelectedIndice], [goingBackDates objectAtIndex:comSelectedIndice]];
I don't whether depPrice
, comPrice
, and price
were allocated correctly, nor what their types are, but they could be causing you problems, as well.我不知道
depPrice
、 comPrice
和price
是否正确分配,也不知道它们的类型是什么,但它们也可能会给您带来问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.