I'm creating a category on NSDate
that that converts a NSDate
into a NSString
. It uses an NSDateFormatter
to do so. I found that allocating then deallocating the formatter each time was causing noticeable delays in my application (this category is used very frequently), so I updated my 'format' method to look like this:
- (NSString *)pretty
{
static NSDateFormatter *formatter = nil;
if (formatter == nil)
{
formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterLongStyle];
[formatter setTimeStyle:NSDateFormatterNoStyle];
}
return [formatter stringFromDate:self];
}
Is this the correct way to handle a static variable in Cocoa? Is this a leak (no dealloc
after alloc
)? Does a better way exist of doing something like this? Thanks!