0

我正在尝试使用 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;

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

提前致谢!

编辑

在此处输入图像描述

4

2 回答 2

1

您的defaultFormatter方法没有返回任何内容,因此您得到一个垃圾值,您尝试将stringFromDate:导致崩溃的消息发送到该值。编译器应该警告你这个,所以总是修复你的编译器警告!

于 2013-01-14T19:07:57.153 回答
0

正如我在评论中提到的,您的方法return中缺少声明。defaultFormatter您应该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;
}
于 2013-01-14T19:08:53.900 回答