【问题标题】:NSDate stringFromDate returning null error?NSDate stringFromDate 返回空错误?
【发布时间】:2013-08-22 05:07:25
【问题描述】:

我正在根据 UITableViewCell 中的字幕文本设置日期。字幕文本是动态生成的,格式为“2013 年 8 月 21 日”。我正在尝试检查字幕文本中的日期是否大于当前日期 [nsdate date] 的 90 天,但出现以下错误。

Before anything: (null)
2013-08-21 23:01:00.656 athletes[806:60b] After NSDate Conversion: (null)
2013-08-21 23:01:00.660 athletes[806:60b] *** -[__NSCFCalendar components:fromDate:toDate:options:]: fromDate cannot be nil
I mean really, what do you think that operation is supposed to mean with a nil fromDate?
An exception has been avoided for now.
A few of these errors are going to be reported with this complaint, then further violations will simply silently do whatever random thing results from the nil.
Here is the backtrace where this occurred this time (some frames may be missing due to compiler optimizations):

这是我试过的代码:

NSString *detailTextDate = lastEval.date_recorded;
NSLog(@"Before anything: %@",detailTextDate);
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateStyle = NSDateFormatterLongStyle;
NSDate *startDate = [dateFormatter dateFromString:detailTextDate];
NSLog(@"After NSDate Conversion: %@",startDate);
[dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
NSDate *todaysDate = [NSDate date];

NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorianCalendar components:NSDayCalendarUnit
                                                    fromDate:startDate
                                                      toDate:todaysDate
                                                     options:0];
if(components.day >= 90 && lastEval.date_recorded != nil){
    cell.detailTextLabel.text = [NSString stringWithFormat:@"%@ was last evaluated on :%@. It has been over 3 months since their last evaluation.",athlete.first, lastEval.date_recorded];
    cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;

【问题讨论】:

  • 正如您的日志所说,您的detailTextDateNULL,这就是您的代码崩溃的原因。仔细检查你是如何得到detailTextDatelastEval.date_recorded的。
  • 你有非常好的和有趣的异常处理程序:)
  • 先检查一下“lastEval.date_recorded”?价值
  • 同时检查“lastEval”是否为 nil。如果是,那么任何访问它的属性的尝试也将返回 nil。
  • @FahriAzimov:谢谢。弄清楚了。请参阅下面的答案。

标签: ios objective-c cocoa-touch uitableview


【解决方案1】:

检查您的 TableViewCell。 NSLog(@"Before anything...)已经打印出(null)。所以detailTextDate没有任何价值。

【讨论】:

  • 就是这样。我添加了一个 if 语句,如下所示: if(lastEval.date_recorded != nil){} 并处理了它。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多