What is the best way to deal with the NSDateFormatter locale “feechur”?

后端 未结 4 1964
花落未央
花落未央 2020-11-21 05:38

It seems that NSDateFormatter has a \"feature\" that bites you unexpectedly: If you do a simple \"fixed\" format operation such as:

NSDateForma         


        
4条回答
  •  一整个雨季
    2020-11-21 06:33

    Duh!!

    Sometimes you have an "Aha!!" moment, sometimes it's more of a "Duh!!" This is the latter. In the category for initWithSafeLocale the "super" init was coded as self = [super init];. This inits the SUPERCLASS of NSDateFormatter but does not init the NSDateFormatter object itself.

    Apparently when this initialization is skipped, setLocale "bounces off", presumably because of some missing data structure in the object. Changing the init to self = [self init]; causes the NSDateFormatter initialization to occur, and setLocale is happy again.

    Here is the "final" source for the category's .m:

    #import "NSDateFormatter+Locale.h"
    
    @implementation NSDateFormatter (Locale)
    
    - (id)initWithSafeLocale {
        static NSLocale* en_US_POSIX = nil;
        self = [self init];
        if (en_US_POSIX == nil) {
            en_US_POSIX = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
        }
        [self setLocale:en_US_POSIX];
        return self;    
    }
    
    @end
    

提交回复
热议问题