0

可能重复:
如果“a == b”在比较两个 NSString 对象时为假?

在“if”语句中,我比较两个字符串“currentDateString”和“dateCreatedString”,如果为真,则为“Today”,如果为假,则为“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]];
}
}

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

谢谢!

4

1 回答 1

4

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

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

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

于 2012-12-03T00:03:58.760 回答