两个NSString值的“if”语句不起作用

时间:2012-12-02 23:59:24

标签: ios if-statement nsstring nsdate

  

可能重复:
  If “a == b” is false when comparing two NSString objects?

在“if”语句中,我正在比较两个字符串“currentDateString”和“dateCreatedString”,如果为true则为“Today”,如果为false则为“dateCreatedString”。尽管在创建新项目时它们应该相等,但if语句每次都返回false,并且当我想要“今天”时只提供currentDateString。

- (NSString *)dateCreatedString
{
// Create a NSDateFormatter that will turn a date into a simple date string
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
NSString *dateCreatedString = [dateFormatter stringFromDate:[_detailItem dateCreated]];
return dateCreatedString;
}
- (NSString *)currentDateString
{
// Create a NSDateFormatter that will turn a date into a simple date string
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
NSString *currentDateString = [dateFormatter stringFromDate:[NSDate date]];
return currentDateString;
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
//places "Today" in the dateLabel if the two strings both equal today
if ([self currentDateString] == [self dateCreatedString] || [_detailItem dateCreated] == nil) {
    [_dateTxt setText:@"Today"];
}
else{
    [_dateTxt setText:[self dateCreatedString]];
}
}

有人可以帮助解释为什么会发生这种情况,以及如何解决这个问题?

谢谢!

1 个答案:

答案 0 :(得分:4)

您应该使用isEqualToString来比较这样的字符串:

if ([[self currentDateString] isEqualToString:[self dateCreatedString]])

使用==比较指向字符串对象的指针,这些指针肯定不一样。