ios - Crash in NSDateformatter setDateFormat method -


-(nsstring*) converttodatestring:(nsstring*)str{      static nsdateformatter *indateformatter = nil;     static nsdateformatter *outdateformatter = nil;     nsstring *outdate = nil;      if([str iskindofclass:[nsstring class]] && [str length] > 0){     nsstring *datestr = [[nsstring alloc] initwithstring:str];         if (indateformatter == nil) {              indateformatter = [[nsdateformatter alloc] init];             indateformatter.dateformat = @"yyyy-mm-dd";         }         if (outdateformatter == nil) {              outdateformatter = [[nsdateformatter alloc] init];             outdateformatter.dateformat = @"mm/dd/yy";         }         nsrange rangeofdash = [datestr rangeofstring:@"t"];         datestr = (rangeofdash.location != nsnotfound) ? [datestr substringtoindex:rangeofdash.location] : datestr;          if([datestr iskindofclass:[nsstring class]] && [datestr length] == 10){ nsdate* date = [indateformatter datefromstring:datestr];             if (date != nil) {                 outdate = [outdateformatter stringfromdate:date];              }         }     }          return outdate; } 

crash occurred in line "indateformatter.dateformat = @"yyyy-mm-dd"; there multiple instances of class gets created in parallel , invokes above method. crash reproducible.

am not using date formatter correctly? in advance

for thread-safe lazy initialization, can use gcd dispatch_once() function:

static nsdateformatter *indateformatter; static nsdateformatter *outdateformatter; static dispatch_once_t oncetoken; dispatch_once(&oncetoken, ^{     indateformatter = [[nsdateformatter alloc] init];     indateformatter.dateformat = @"yyyy-mm-dd";     outdateformatter = [[nsdateformatter alloc] init];     outdateformatter.dateformat = @"mm/dd/yy"; }); 

Comments

Popular posts from this blog

ios - UICollectionView Self Sizing Cells with Auto Layout -

node.js - ldapjs - write after end error -

DOM Manipulation in Wordpress (and elsewhere) using php -