The correct way to set the static object required for a method

I create a category on NSDatewhich converts a NSDateto NSString. Used for this NSDateFormatter. I found that highlighting, then releasing the formatting each time caused noticeable delays in my application (this category is used very often), 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 right way to handle a static variable in Cocoa? Is it a leak (not deallocafter alloc)? Is there a better way to do something like this? Thank!

+5
source share
2

. , . , , .

.. , .

pretty ( , NSDateFormatter - , , ), .

static dispatch_once_t onceMark;
static NSDateFormatter *formatter = nil;
dispatch_once(&onceMark, ^{
        formatter = [[NSDateFormatter alloc] init];
        [formatter setDateStyle:NSDateFormatterLongStyle];
        [formatter setTimeStyle:NSDateFormatterNoStyle];
});
+9

, , , , , , , .

, NSDateFormatter , , NSDateFormatter .

-1

All Articles