12. 缓存 NSDateFormatter

作者: 拿破仑的风火轮_

为什么要缓存 NSDateFormatter ?

Creating a date formatter is not a cheap operation. If you are likely to use a formatter frequently, it is typically more efficient to cache a single instance than to create and dispose of multiple instances. One approach is to use a static variable.

思路: 利用 NSCache, 以 stringFormatter+NSLocalelocaleIdentifierkey 缓存 NSDateFormatter. 当UIApplicationDidReceiveMemoryWarningNotificationNSCurrentLocaleDidChangeNotification 释放 NSCache 缓存的对象.

代码参考 BTNSDateFormatterFactory.m, 核心实现代码如下:

- (NSDateFormatter *)dateFormatterWithFormat:(NSString *)format andLocale:(NSLocale *)locale {
    @synchronized(self) {
        NSString *key = [NSString stringWithFormat:@"%@|%@", format, locale.localeIdentifier];

        NSDateFormatter *dateFormatter = [loadedDataFormatters objectForKey:key];
        if (!dateFormatter) {
            dateFormatter = [[NSDateFormatter alloc] init];
            dateFormatter.dateFormat = format;
            dateFormatter.locale = locale;
            [loadedDataFormatters setObject:dateFormatter forKey:key];
        }

        return dateFormatter;
    }
}

Last updated