Skip to content

Instantly share code, notes, and snippets.

@ikura
Created August 11, 2013 03:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ikura/6203324 to your computer and use it in GitHub Desktop.
Save ikura/6203324 to your computer and use it in GitHub Desktop.
//
// NSDateFormatter+IkuramediaLazyFormatter.h
//
// Created by Price Stephen on 11/08/2013.
// For Ikura Group Limited.
//
#import <Foundation/Foundation.h>
typedef void(^IMLazyDateFormatterBlock)(NSDateFormatter *);
typedef NSString* IMLazyDateFormatterToken;
@interface NSDateFormatter (IkuramediaLazyFormatter)
/***
Snippet: IMKeyedLazyFormatter
NSDateFormatter *dateFormatter = [NSDateFormatter lazyDateFormatterWithKey:<#Key#>
configurationBlock:^(NSDateFormatter *dateFormatter)
{
<#code#>
}];
***/
+ (NSDateFormatter *)lazyDateFormatterWithKey:(NSString *)key
configurationBlock:(IMLazyDateFormatterBlock)configurationBlock;
/***
Snippet: IMLazyFormatter
static IMLazyDateFormatterToken dateToken;
NSDateFormatter *dateFormatter = [NSDateFormatter lazyDateFormatterWithToken:&dateToken
configurationBlock:^(NSDateFormatter *dateFormatter)
{
<#code#>
}];
***/
+ (NSDateFormatter *)lazyDateFormatterWithToken:(IMLazyDateFormatterToken __strong*)token
configurationBlock:(IMLazyDateFormatterBlock)configurationBlock;
@end
//
// NSDateFormatter+IkuramediaLazyFormatter.m
//
// Created by Price Stephen on 11/08/2013.
// For Ikura Group Limited.
//
#import "NSDateFormatter+IkuramediaLazyFormatter.h"
@implementation NSDateFormatter (IkuramediaLazyFormatter)
static NSMutableDictionary *imLazyDictionary = nil;
+ (NSDateFormatter *)lazyDateFormatterWithToken:(NSString * __strong*)tokenString
configurationBlock:(IMLazyDateFormatterBlock)configurationBlock;
{
if (*tokenString == nil)
{
*tokenString = [[NSUUID UUID] UUIDString];
}
return [self lazyDateFormatterWithKey:*tokenString
configurationBlock:configurationBlock];
}
+ (NSDateFormatter *)lazyDateFormatterWithKey:(NSString *)identifier
configurationBlock:(IMLazyDateFormatterBlock)configurationBlock;
{
if (imLazyDictionary == nil)
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
imLazyDictionary = NSMutableDictionary.dictionary;
});
}
@synchronized(self)
{
if (imLazyDictionary[identifier]) return imLazyDictionary[identifier];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
if (configurationBlock) configurationBlock(dateFormatter);
imLazyDictionary[identifier] = dateFormatter;
return dateFormatter;
}
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment