[英]NSDateFormatter crashing
我正在尝试使用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;
我在这里看到了一些类似的问题,但无法解决此问题!
提前致谢!
编辑
您的defaultFormatter
方法不返回任何内容,因此您会获得一个垃圾值,尝试将stringFromDate:
消息发送至该值,这会导致崩溃。 编译器应对此发出警告,因此请务必修复编译器警告!
如我的评论所述,您的defaultFormatter
方法中缺少return
语句。 设置值后,您应该返回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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.