我正在尝试将对象数组存储在可变字典中,但似乎字典正在丢失我的一些数组(或者数组正在丢失数据?)。
无论如何,这就是我所在的位置:
- (NSDictionary *)getTicketsByDay:(NSArray *)tickets {
// take an array of tickets and return a dictionary with dates (given by
// NSDateFormatterShortStyle) as keys and arrays of tickets as the values
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterShortStyle];
// get NSDate object without time (only month, day, year)
unsigned int flags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSCalendar *calendar = [NSCalendar currentCalendar];
NSMutableDictionary *datesDict = [[NSMutableDictionary alloc] init];
for (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;
}
但是然后在控制台上,在随机的地方(虽然每次都在同一个地方),我得到了类似的东西
41
41
42
0
it's here: 6/29/12
1
即使先前对象的键也是“6/29/12”。我还让它打印了字典中的所有键,只有 1 个。
所以在某个地方我正在丢失我的数据。这是怎么回事?
我还应该提到我在 10.7.4 并使用 ARC。