在NSDateformatter setDateFormat方法中崩溃

时间:2013-08-12 19:23:12

标签: ios

-(NSString*) convertToDateString:(NSString*)str{

    static NSDateFormatter *InDateFormatter = nil;
    static NSDateFormatter *OutDateFormatter = nil;
    NSString *outDate = nil;

    if([str isKindOfClass:[NSString class]] && [str length] > 0){
    NSString *dateStr = [[NSString alloc] initWithString:str];
        if (InDateFormatter == nil) {

            InDateFormatter = [[NSDateFormatter alloc] init];
            InDateFormatter.dateFormat = @"yyyy-MM-dd";
        }
        if (OutDateFormatter == nil) {

            OutDateFormatter = [[NSDateFormatter alloc] init];
            OutDateFormatter.dateFormat = @"MM/dd/yy";
        }
        NSRange rangeOfDash = [dateStr rangeOfString:@"T"];
        dateStr = (rangeOfDash.location != NSNotFound) ? [dateStr substringToIndex:rangeOfDash.location] : dateStr;

        if([dateStr isKindOfClass:[NSString class]] && [dateStr length] == 10){
NSDate* date = [InDateFormatter dateFromString:dateStr];
            if (date != nil) {
                outDate = [OutDateFormatter stringFromDate:date];

            }
        }
    }

        return outDate;
}

行中发生崩溃" InDateFormatter.dateFormat = @" yyyy-MM-dd&#34 ;;  将有多个并行创建的类实例并调用上述方法。崩溃很少可以重现。

我没有正确使用日期格式化程序吗?提前致谢

1 个答案:

答案 0 :(得分:4)

对于线程安全的延迟初始化,您可以使用GCD dispatch_once() 功能:

static NSDateFormatter *inDateFormatter;
static NSDateFormatter *outDateFormatter;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
    inDateFormatter = [[NSDateFormatter alloc] init];
    inDateFormatter.dateFormat = @"yyyy-MM-dd";
    outDateFormatter = [[NSDateFormatter alloc] init];
    outDateFormatter.dateFormat = @"MM/dd/yy";
});