sortedArray contains 100+ objects that need to be organize by the ‘hour’ in the ‘time’ key. The outcome is to have an array of arrays to populate the sections of a table and use the hour for the index. ‘time’ is of the form – 2012-05-15 07:20:00
NSInteger d = 0;
NSInteger prevd;
NSMutableArray *tempArray = [[NSMutableArray alloc] init];
detailArray = [[NSMutableArray alloc] init];
for (NSInteger i = 0; i < 24; ++i)
[detailArray addObject:[NSNull null]];
for (NSArray *item in sortedArray) {
prevd = d;
d = [[[[item objectAtIndex:0] objectForKey:@"time"] substringWithRange:NSMakeRange(11, 2)] intValue];
if (d > prevd && prevd != 0) {
[detailArray replaceObjectAtIndex:d withObject:tempArray];
[tempArray removeAllObjects];
}
[tempArray addObject:item];
}
The objects are not ending up in the correct detailArray postition or not ending up in it at all. For instance, [detailArray objectAtIndex:6] give items with time 14 (2pm).
What am I missing?
Edit to correct code with 1st answer. It is now:
NSInteger d = 0;
NSInteger prevd;
NSMutableArray *tempArray = nil;
detailArray = [[NSMutableArray alloc] init];
for (NSInteger i = 0; i < 24; ++i)
[detailArray addObject:[NSNull null]];
for (NSArray *item in sortedArray) {
prevd = d;
d = [[[[item objectAtIndex:0] objectForKey:@"time"] substringWithRange:NSMakeRange(11, 2)] intValue];
if (d > prevd) {
tempArray = NSMutableArray array];
[detailArray replaceObjectAtIndex:d withObject:tempArray];
}
[tempArray addObject:item];
}
You can’t reuse tempArray like that, you’re going to end up with detailArray containing multiple entries that all point to the same tempArray instance. (i.e. every slot that had a time is going to end up with the array for the last time slot).
Instead of
you’ll want
that way each time slot has its own array.
And you’ll also want to change your original declaration of tempArray to be