ios - NSDateFormatter 崩溃

标签 ios objective-c nsdate nsdateformatter

我尝试使用 NSDateFormatter 格式化日期,但我的应用因 EXC_BAD_ACCESS 崩溃。

代码如下:

DateInputTableViewCell *cell0 = (DateInputTableViewCell *)[paramTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
DateInputTableViewCell *cell1 = (DateInputTableViewCell *)[paramTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];

NSString *fromDate = [[Helpers defaultFormatter] stringFromDate:cell0.dateValue];
NSString *toDate = [[Helpers defaultFormatter] stringFromDate:cell1.dateValue];

上面的代码我从我拥有的两个自定义 UITableViewCell 中获取日期。这些值不为空(我已经测试过)。但是,当我尝试使用 Helpers 类中的 defaultFormatter 方法时,应用程序崩溃了。下面是代码:

+ (NSDateFormatter *)defaultFormatter{
    defaultFormatter = [[NSDateFormatter alloc] init];
    NSLocale* locale = [[NSLocale alloc] initWithLocaleIdentifier:@"pt_BR"];
    [defaultFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"America/Sao_Paulo"]];
    [defaultFormatter setDateFormat:@"yyyy'-'MM'-'dd' 'HH':'mm':'ss"];
    [defaultFormatter setLocale:locale];
    [locale release];
    return defaultFormatter;
}

自定义 UITableViewCell 的 NSDateFormatter 定义如下:

self.dateFormatter = [[NSDateFormatter alloc] init];
self.dateFormatter.timeStyle = NSDateFormatterNoStyle;
self.dateFormatter.dateStyle = NSDateFormatterMediumStyle;

我在这里看到了一些类似的问题,但无法解决这个问题!

提前致谢!

编辑

enter image description here

最佳答案

您的 defaultFormatter 方法没有返回任何内容,因此您会得到一个垃圾值,您尝试向该值发送 stringFromDate: 消息,这会导致崩溃。编译器应该对此发出警告,因此请务必修复编译器警告!

关于ios - NSDateFormatter 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14324849/

相关文章:

objective-c - 如何向 NSDate 添加时间间隔?

ios - "NSString stringWithFormat:"和 "%zd"在 32 位设备中的奇怪行为

ios - 如何从 Realm 文件中删除一个类

xcode - swift:如何计算日期间隔(今天~指定日期)

ios - 考虑语言环境设置等的一些 NSDate 问题

ios - 使用 MMWormhole 将消息传递给 Apple Watch

ios - 如何在应用程序中显示 PDF URL 文件并打开或查看 PDF 文件的下一页,如 iBook

ios - SWIFT:在 performSegueWithIdentifier 之后未加载原型(prototype)单元格

iOS7 - 设备唯一标识符

objective-c - 自定义 DatePicker 的算法