objective c - NSMutableDictionary losing object -
i'm trying store arrays of objects in mutable dictionary, seems dictionary losing of arrays (or maybe arrays losing data?).
anyways, here's i'm at:
- (nsdictionary *)getticketsbyday:(nsarray *)tickets { // take array of tickets , return dictionary dates (given // nsdateformattershortstyle) keys , arrays of tickets values nsdateformatter *formatter = [[nsdateformatter alloc] init]; [formatter setdatestyle:nsdateformattershortstyle]; // nsdate object without time (only month, day, year) unsigned int flags = nsyearcalendarunit | nsmonthcalendarunit | nsdaycalendarunit; nscalendar *calendar = [nscalendar currentcalendar]; nsmutabledictionary *datesdict = [[nsmutabledictionary alloc] init]; (ticket *ticket in tickets) { nsdatecomponents *ticketdatenotimecomponents = [calendar components:flags fromdate:[ticket createdat]]; nsdate *ticketdatenotime = [calendar datefromcomponents:ticketdatenotimecomponents]; nsstring *datestring = [formatter stringfromdate:ticketdatenotime]; nsmutablearray *ticketarray = [datesdict objectforkey:datestring]; nslog(@"%lu", [ticketarray count]); if (ticketarray == nil) { nslog(@"it's here: %@", datestring); ticketarray = [[nsmutablearray alloc] init]; } [ticketarray addobject:ticket]; nslog(@"%lu", [ticketarray count]); [datesdict setobject:ticketarray forkey:datestring]; } return datesdict; }
but on console, @ random places (although same places every time),
41 41 42 0 it's here: 6/29/12 1
even though key previous objects "6/29/12". i've had print keys in dictionary , there 1.
so somewhere i'm losing data. what's going on?
i should mention i'm on 10.7.4 , using arc.
the code looks fine me (if include suggestions @conradshultz)
note don't need create ticketdatenotime since you're using date format, generate short format string if date contains time...
so code simplified to:
- (nsdictionary *)getticketsbyday:(nsarray *)tickets { // take array of tickets , return dictionary dates (given // nsdateformattershortstyle) keys , arrays of tickets values nsdateformatter *formatter = [[nsdateformatter alloc] init]; [formatter setdatestyle:nsdateformattershortstyle]; nsmutabledictionary *datesdict = [[nsmutabledictionary alloc] init]; (ticket *ticket in tickets) { nsstring *datestring = [formatter stringfromdate:[ticket createdat]]; nsmutablearray *ticketarray = [datesdict objectforkey:datestring]; nslog(@"%lu", [ticketarray count]); if (ticketarray == nil) { nslog(@"it's here: %@", datestring); ticketarray = [[nsmutablearray alloc] init]; [datesdict setobject:ticketarray forkey:datestring]; } [ticketarray addobject:ticket]; nslog(@"%lu", [ticketarray count]); } return datesdict; }
Comments
Post a Comment