Use a static variable inside an Objective-C category

ios, iphone, objective-c

Solution

Categories will only let you maintain static variables. But for your instance that would work perfectly.

Make a category for your formatter as so

Header

@interface NSDateFormatter (myFormats)

+ (NSDateFormatter*) specialFormatting;

@end

Implementation file

@implementation NSDateFormatter (myFormats)

+ (NSDateFormatter*) specialFormatting{
    static NSDateFormatter *_specialFormatting;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _specialFormatting = [[NSDateFormatter alloc] init];
        // Continue Setting up this format;
    });
    return _specialFormatting;
}

@end

Then be sure to include your header where you want to use this (i use the prefix.pch file to include things I use all the time)

then you will not need to declare it and can use it from where it is. And the item will not be created each time you need it..

The object is never released. but that is what you desire anyhow. since it is still accessible it is not a memory leak.

You can also provide helper methods that will allow you to just get back the string.

Hope that helps.

Problem

I want to be able to do the following: ``` NSString *hoursAndMinutes = [myNSDateObject formattedTime]; // eg. 10:25 ``` Now I can create a category on the `NSDate` class but since the creation of `NSDateFormatter` has proven to be quite costly I would like to use a single instance of my `NSDateFormatter`. Is this a contradiction to the notion of categories or is there a neater way to achieve this?

Original source

Related problems