也许这不是最快的方法,但我认为它很简单
首先创建一个像这样的小型内部类:
@interface ProductSection
@property (strong, nonatomic) NSString* sectionName;
@property (strong, nonatomic) NSMutableArray* products;
@end
然后用这个代替你的排序:
NSSortDescriptor *aSort =[[NSSortDescriptor alloc] initWithKey:@"Dis" ascending:YES];
NSArray* products = [distribArray sortUsingDescriptors:[NSMutableArray arrayWithObject:aSort]];
self.sections = [NSMutableArray array];
NSString* currentDistributor = nil;
for (Product* p in products) {
if (![p.Dis isEqualToString:currentDistributor]) {
ProductSection* section = [[ProductSection alloc] init];
section.sectionName = p.Dis;
section.products = [NSMutableArray array];
[self.sections addObject:section];
currentDistributor = p.Dis;
}
ProductSection* section = [self.sections lastObject];
[section.products addObject:p];
}
[self.tableView reloadData];
哪里self.sections
是一个可变数组ProductSection
接下来在你的Table View Data Source
:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [[[self.sections objectAtIndex:section] products] count];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [self.sections count];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
[[self.sections objectAtIndex:section] sectionName];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
Product* p = [[[self.sections objectAtIndex:indexPath.section] products] objectAtIndex:indexPath.row];
...
}
希望这会有所帮助