Reputation: 2488
my ios application requires heavy use of NSDateFormatter, i know that creating a instance of NSDateFormatter is expensive, however creating few singleton instances is fine, but i need to use lot of date formats , which i cannot create instance for all of these formats,
what am doing is creating an singleton NSDateFormatter with common settings like timezone , locale, and whenever i want i will clone the nsdateformatter and make change to that,
my question is
does copy is better than clone?
what would be the best practice to handle many date formats ?
Upvotes: 2
Views: 709
Reputation: 318854
I can't speak to the performance issues (run your own tests to see which is faster).
But what I would do is create a dictionary of date formatters using the date format as the key.
Write a method like the following:
- (NSDateFormatter *)dateFormatterForFormat:(NSString *)dateFormat {
NSDateFormatter *formatter = formats[dateFormat];
if (!formatter) {
formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:dateFormat];
// any other setup needed
formats[dateFormat] = formatter;
}
return formatter;
}
In the code, formats
is some NSMutableDictionary
ivar or static variable you setup in the class.
Upvotes: 0
Reputation: 41821
Unfortunately, the expense of date formatter setup is incurred the first time you use it after either creating it or setting any properties of it. So you won't be able to avoid the cost at least once for each configuration of formatter you use.
I have a few suggestions:
Upvotes: 3