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!
You are effectively creating a singleton. Unless it isn't going to be used throughout the entire running session of your application, don't worry about the memory use. Even if it is only going to be used intermittently, leaving one date formatter around isn't going to be an issue.
I.e. just like a singleton, don't worry about releasing the object prior to application termination.
If pretty
were to be pounded on from multiple threads (and assuming that NSDateFormatter
itself is thread safe -- I didn't check the docs and, thus, don't write the code without verifying thread safety), then you'd want to protect the initialization.
static dispatch_once_t onceMark;
static NSDateFormatter *formatter = nil;
dispatch_once(&onceMark, ^{
formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterLongStyle];
[formatter setTimeStyle:NSDateFormatterNoStyle];
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With