Let’s say that my UITableView is fed by an array of X amount of NSDates. How can I sort them so that the UITableView mimicking the Phone app on the iPhone, but in a way so that there is a section in the UITableView for each day that is represented by a date (or more than one date) in the array?
Edit: Breakthrough! To figure out how many sections I need, I use this:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
NSArray* array = [[NSUserDefaults standardUserDefaults] objectForKey:@"mapSaveDataKey"];
NSMutableArray* dateStrings = [[NSMutableArray alloc] init];
for(NSArray* innerArray in array)
[dateStrings addObject:[dateFormatter stringFromDate:[innerArray objectAtIndex:13]]];
NSArray *cleanedArray = [[NSSet setWithArray:dateStrings] allObjects];
return [cleanedArray count];
}
By taking an array of the dateStrings which are formatted NSDates using an NSDateFormatter with these settings:
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setDoesRelativeDateFormatting:YES];
I can get a list of string dates, with each string from the same day being the same regardless of time. Then I can use an NSSet to get an array of the same strings excluding duplicates, and the count of that array is the number of sections I need. Great.
Now on to the hard part: how can I take that array of strings (or the original array of NSDates) and figure out how many duplicates there are of each day, and use that information to decide how many rows are needed in each section of the UITableView? And to make things more difficult, they need to be ordered from recent to old. (There is also the matter of figuring out which cells need to go in which section, but that can be figured out later)
Solved, thanks to an eloquent solution from Ole Begemann. +100 to you
I use this loop to figure out when in my array I need to start for each section:
int offset = 0;
for(int idx = 0; idx < [tableViewOutlet numberOfSections]; idx++) {
if(idx == indexPath.section)
break;
offset += [tableViewOutlet numberOfRowsInSection:idx];
}
Personally, I would not use date formatters. Handling strings feels somewhat “dirty” if you have more “numeric” values (dates) available. Using
NSDateComponents, it is just as easy to split the date from the time components of anNSDate. The following sample code is pretty long but it should be simple to understand. Given an array of (sample)NSDateobjects (in thedatesvariable), it generates asectionsdictionary.The keys of the dictionary are
NSDateinstances that represent a certain day (their time component is mignight in the time zone of the used calendar). The values of the dictionary are arrays containing the actual dates that belong to a certain section (sorted). You should be able to populate your table view with that info.Edit: I took this question as an opportunity to write a blog post about this problem.