NSString compare is throwing exception SIGABT

大兔子大兔子 提交于 2020-01-06 08:01:18

问题


I have following code, where I'm comparing two string but its throwing exception.

- (void)calendarMonthView:(TKCalendarMonthView *)monthView didSelectDate:(NSDate *)d {
NSLog(@"calendarMonthView didSelectDate %@",d);
//[self papulateTable];
//[table reloadData];
 //[self performSelector:@selector(papulateTable) withObject:nil afterDelay:1.0];
NSString *tempDate = (NSString*)d;
NSString *selectedDate = @"2013-02-04 00:00:00 +0000";
if([tempDate isEqualToString:selectedDate])
{
  flagtoCheckSelectedCalendarDate = 1;
}
if(flagtoCheckSelectedCalendarDate == 1)
{
    [self viewDidLoad];
}
if(flagtoCheckSelectedCalendarDate == 2)
{
    [self viewDidLoad];
}
//[table reloadData];

}

Could any one please suggest.Thanks.


回答1:


Casting an NSDate object to NSString does not make it a string. To compare dates, you're going to have to transform the NSString into an NSDate using an NSDateFormatter. After that, you can use NSDate's instance method isEqualToDate: for your comparison.

NSString *selectedDate = @"2013-02-04 00:00:00 +0000";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
[dateFormatter setDateFormat:@"yyyy-MM-DD hh:mm:ss ZZZZ"];
NSDate *actualDate = [dateFormatter dateFromString:selectedDate];


if ([actualDate isEqualToDate:d]) {
   ...
}



回答2:


d is of type NSDate and not NSString, therefore -isEqualToString: results in a crash.
You shouldn't compare strings here, but the dates. Use NSDate's -compare: method and change

NSString *selectedDate = @"2013-02-04 00:00:00 +0000";

to

NSDate *selectedDate = [NSDate ...];



回答3:


You are casting an NSDate object to NSString without converting it. You will have to format the NSDate as a string into your expected date format before you can compare it with your selectedDate. See this previous answer or this one for examples




回答4:


You are comparing NSDate and NSString. You would need to change the NSDate to string using a date formatter first.



来源:https://stackoverflow.com/questions/14644329/nsstring-compare-is-throwing-exception-sigabt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!