dateFromString:crash Objective C

时间:2013-08-19 05:47:24

标签: objective-c exc-bad-access nsdateformatter

我使用以下代码从特定格式的NSString创建NSDate。

+ (NSDateFormatter *)serverFormatter
{
    static NSDateFormatter *formatter = nil;

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyy-MM-dd'T'HHmmssZ"];
    });

    return formatter;
}

+ (NSDate *)dateFromServerDateString:(NSString *)dateString
{
    if (!dateString) {
        return nil;
    }

    NSDateFormatter *formatter = [NSDate serverFormatter];
    NSString *cleaned = [dateString stringByReplacingOccurrencesOfString:@":"
                                                           withString:@""];

    return [formatter dateFromString:cleaned];
}

每次在蓝色的月亮中我都会在return [formatter dateFromString:cleaned];上收到一个EXC_BAD_ACCESS查看堆栈跟踪显示clean,dateString和formatter都有正确的值(不是nil和'po'打印正确的值在控制台中。)

在做了一些阅读之后,我确实发现我的代码需要考虑NSDateFormatter上的线程安全性。 (我已经适当地调整了我的代码,这里没有显示。)但是根据堆栈跟踪,崩溃发生时只有一个线程正在访问我的NSDateFormatter。

具有异常的堆栈跟踪如下所示。

#0  0x02d09ad1 in typeinfo name for icu::UObject ()
#1  0x02b8f5ed in icu::TimeZone::getOffset(double, signed char, int&, int&, UErrorCode&) const ()
#2  0x02b95652 in icu::Calendar::computeTime(UErrorCode&) ()
#3  0x02b95552 in icu::Calendar::updateTime(UErrorCode&) ()
#4  0x02b96036 in icu::Calendar::getTimeInMillis(UErrorCode&) const ()
#5  0x02c4244f in icu::DateFormat::parse(icu::UnicodeString const&, icu::ParsePosition&) const ()
#6  0x02cebd05 in udat_parse ()
#7  0x029b7161 in CFDateFormatterGetAbsoluteTimeFromString ()
#8  0x029b6f8e in CFDateFormatterCreateDateFromString ()
#9  0x0214e7e9 in getObjectValue ()
#10 0x0214e701 in -[NSDateFormatter getObjectValue:forString:errorDescription:] ()
#11 0x0214ea3f in -[NSDateFormatter dateFromString:] ()
#12 0x0001a7a4 in +[NSDate(RDUtilities) dateFromServerDateString:]
...

之前有没有人遇到这样的事情并且有任何调试技巧?

1 个答案:

答案 0 :(得分:0)

调试方法如下:

+ (NSDate *)dateFromServerDateString:(NSString *)dateString
{
    if (!dateString) {
        return nil;
    }
    NSLog (@"%@", dateString);
    NSDateFormatter *formatter = [NSDate serverFormatter];
    NSString *cleaned = [dateString stringByReplacingOccurrencesOfString:@":"
                                                           withString:@""];
    NSLog (@"%@", cleaned);  //see if cleaned represents proper string with separators
    NSLog (@"%@", formatter); //not null?

    return [formatter dateFromString:cleaned];
}

请注意,您的格式必须符合described here一个格式。 如需进一步参考,请阅读this

<强>更新

以下是您的操作方法:

+ (NSDateFormatter *)serverFormatter
{
    static NSDateFormatter *formatter = nil;

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
      if (formatter == nil) {
        formatter = [[NSDateFormatter alloc] init];
      }
        [formatter setDateFormat:@"yyyy-MM-dd'T'HHmmssZ"];
    });

    return formatter;
}