Created
July 23, 2012 15:24
-
-
Save andrewgarn/3164221 to your computer and use it in GitHub Desktop.
Making NSDateFormatter thread safe
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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