I’m using a NSDateFormatter object (customized for specific purposes) multiple times. Since I’m not a objc expert, I figured out three different approaches to deal with it.
In the first one, I’ve created a NSDateFormatter category and customized the code there. This is common approach but each time I create such an object, this is put in the main autorelease pool. This behaviour, I think, is valid both for non-ARC and ARC code.
In the second instead, I’ve overridden the +(void)initialize method and put the customization code there. Here a simple example:
static NSDateFormatter* dateFormatter = nil;
+(void)initialize
{
dateFormatter = [[NSDateFormatter alloc] init];
// other code here
}
Finally, I set up a third approach using a lazy loading instantiation through properties like the following:
-(NSDateFormatter)dateFormatter
{
if(dateFormatter) return dateFormatter;
// alloc-init here
}
Said this, I would like to know what approach is the most suitable to deal with objects multiple times and if, using +(void)initialize in that manner, is correct.
Thank you in advance.
Both later methods are correct, but I believe you want to put them together!
Note: Such classes are called singletons. Read more