0

Possible Duplicate:
If “a == b” is false when comparing two NSString objects?

In an "if" statement I'm comparing two strings, "currentDateString" and "dateCreatedString", to get "Today" if true and "dateCreatedString" if false. Although they should be equal when creating a new item, the if statement is returning false every time and just giving the currentDateString when I'm looking to get "today".

- (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]];
}
}

Could somebody help explain why this is happening, and how to fix it?

Thanks!

Community
  • 1
  • 1
RoboArch
  • 453
  • 1
  • 6
  • 17

1 Answers1

4

You should use isEqualToString to compare strings like this:

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

Using == you are comparing the pointers to the string objects, which certainly are not the same.

vacawama
  • 150,663
  • 30
  • 266
  • 294