Skip to content

Instantly share code, notes, and snippets.

@andrewgarn
Created July 23, 2012 15:24
Show Gist options
  • Save andrewgarn/3164221 to your computer and use it in GitHub Desktop.
Save andrewgarn/3164221 to your computer and use it in GitHub Desktop.
Making NSDateFormatter thread safe
//
// NSDate+AGCategory.h
// AGFoundation
//
// Created by Andrew Garn on 23/07/2012.
// Copyright (c) 2012 Andrew Garn. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface NSDate (AGCategory)
+ (NSDateFormatter *)dateFormatterWithDateFormat:(NSString *)dateFormat;
@end
//
// NSDate+AGCategory.m
// AGFoundation
//
// Created by Andrew Garn on 23/07/2012.
// Copyright (c) 2012 Andrew Garn. All rights reserved.
//
#import "NSDate+AGCategory.h"
@implementation NSDate (AGCategory)
+ (NSDateFormatter *)dateFormatterWithDateFormat:(NSString *)dateFormat
{
NSMutableDictionary *threadDictionary = [[NSThread currentThread] threadDictionary];
NSString *threadDictionaryKey = [NSString stringWithFormat:@"NSDateAGCategoryDateFormatter-%@", dateFormat];
NSDateFormatter *dateFormatter = [threadDictionary objectForKey:threadDictionaryKey];
if (dateFormatter == nil)
{
dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setCalendar:[NSCalendar currentCalendar]];
[dateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
[threadDictionary setObject:dateFormatter forKey:threadDictionaryKey];
}
// Ensure the dateformatter is using the correct format.
if (![[dateFormatter dateFormat] isEqualToString:dateFormat])
[dateFormatter setDateFormat:dateFormat];
// Reset the timeZone that the dateFormatter uses.
if (![[dateFormatter timeZone] isEqual:[NSTimeZone localTimeZone]])
[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
// Reset the locale that the dateFormatter uses.
if (![[dateFormatter locale] isEqual:[NSLocale autoupdatingCurrentLocale]])
[dateFormatter setLocale:[NSLocale autoupdatingCurrentLocale]];
return dateFormatter;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment