0
-(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"; 行将有多个并行创建的类实例并调用上述方法。崩溃很少可重现。

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

4

1 回答 1

4

对于线程安全的延迟初始化,可以使用 GCDdispatch_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";
});
于 2013-08-12T20:06:04.763 回答