您可以将所有事件保存到以日期为键的字典中。
假设您在 header(.h) 文件中有_eventsDictionary
和_events
作为 ivar。NSMutableDictionary *_eventsDictionary;
NSArray *_events
- (void)reloadTableData {
_eventsDictionary = [NSMutableDictionary dictionary];
for (Event *ev in _events) {
NSMutableArray *eventArray = [_eventsDictionary objectForKey:ev.date];
if (! eventArray) {
// first event for this date
eventArray = [NSMutableArray array];
[_eventsDictionary setObject:eventArray forKey:ev.date];
}
[eventArray addObject:ev];
}
[self.tableView reloadData];
}
现在您拥有数组中的所有事件,这些事件位于_eventsDictionary
.
- (NSString *)dateStringAtIndex:(NSInteger)index {
// Actually I prefer sort them as date objects
// Since you have all dates as string, it should ok for you
NSArray *allSortedKeys = [[_eventsDictionary allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
return [allSortedKeys objectAtIndex:index];
}
- (NSArray *)eventsArrayAtIndex:(NSInteger)index {
NSArray *eventsArray = [_eventDictionary objectForKey:[self dateStringAtIndex:index]];
return eventsArray;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return _eventDictionary.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [[self eventsArrayAtIndex:section] count];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
return [self dateStringAtIndex:section];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
cell = .....
.....
NSArray *eventsArray = [self eventsArrayAtIndex:indexPath.section];
Event *ev = [eventsArray objectAtIndex.row];
// configure your cell with the event
// eg. cell.textLabel.text = ev.time
return cell;
}
现在,您可以在事件数组中的事件之后在某处调用 [self reloadTableData],它为您完成了这项工作。