NSDateFormatter in a single class, or one per section for less expensive code?

I've seen multiple threads, users creating categories to share a static instance NSDateFormatter

.

My application has multiple sections and a class singleton

, each section has multiple views and some views use NSDateFormatter

. I use singleton

to exchange data between partitions without repeating network connections.

I'm a little worried about cost formatters

, and to solve this problem, I could create a method for my class singleton

and alloc

, init

a formatter

there, and it would be all the time, I could use category

, or I could create it in the main view of each section. so at least I wouldn't need this for every view.

I'm guessing the method on mine singleton

would look like this?

+ (NSDateFormatter *)sharedDateFormatter
{
    static NSDateFormatter *sharedDateFormatter = nil ;
    if (sharedDateFormatter == nil)
    {
        sharedDateFormatter = [[NSDateFormatter alloc] init] ;
        [sharedDateFormatter setLocale: [[[NSLocale alloc] initWithLocaleIdentifier: @"en_GB"] autorelease]] ;
        [sharedDateFormatter setDateFormat: @"YYYY-MM-dd HH:mm:ss ZZZ"] ;
    }
    return sharedDateFormatter ;
}

      

My question is, what is the best practice for reducing cost NSDateFormatters

?

+3


source to share


1 answer


The syntax is ok, but I would use the dispatch_once pattern.



Problem: NSDateFormatter is not thread safe. If you are using the same NSDateFormatter on only one thread, or for example on the same sequential dispatch queue, this is fine. Otherwise, you need to either make your code flow safe or use multiple NSDateFormatters, one per thread.

+3


source







All Articles