Not sure I entirely understand the question, but I'll take a stab. So the first step sounds like you want to sort the array of dictionaries based on the @"categories"
key. This will put the array in alphabetical order based on that key:
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"categories" ascending:YES];
NSArray *sortedArray = [arrayOfDictionaries sortedArrayUsingDescriptors:@[sortDescriptor]];
Then you want the section headers of the table to be the names of the categories. First you will need to find out how many different categories there are. A method like this can get that into an array without duplicates:
+ (NSArray *)findCategoriesInArray:(NSArray *)arrayOfDictionaries
{
NSMutableArray *categories = [NSMutableArray array];
for (id object in arrayOfDictionaries) {
if ([object isKindOfClass:[NSDictionary class]]) {
NSDictionary *dictionary = (NSDictionary *)object;
if (dictionary[@"categories"] && ![categories containsObject:dictionary[@"categories"]]) {
[categories addObject:dictionary[@"categories"]];
}
}
}
return categories;
}
At this point you have an array of all the dictionaries sorted by the categories key and an array containing the different categories. Let's assume the categories array from the method above gets assigned to a property self.categories
(which is an NSArray). So now we can populate the section headers in the normal method calls:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return self.categories.count;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return (NSString *)self.categories[section]; // I'm assuming these are all strings
}
Finally, we can populate the rows in each section:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSString *headerTitle = (NSString *)self.categories[section];
return [NameOfClass findNumberOfCategory:headerTitle inArray:self.arrayOfDictionaries];
}
+ (NSInteger)findNumberOfCategory:(NSString *)category inArray:(NSArray *)arrayOfDictionaries
{
NSInteger number = 0;
for (id object in arrayOfDictionaries) {
if ([object isKindOfClass:[NSDictionary class]]) {
NSDictionary *dictionary = (NSDictionary *)object;
if (dictionary[@"categories"] && [dictionary[@"categories"] isKindOfClass:[NSString class]]) {
NSString *thisCategory = (NSString *)dictionary[@"categories"];
if ([thisCategory isEqualToString:category]) {
number++;
}
}
}
}
return number;
}
Assuming both the self.arrayOfDictionaries
and the self.categories
arrays are both in alphabetical order, you can populate the cells themselves in tableView:cellForRowAtIndexPath:
by getting the properties of the object from self.arrayOfDictionaries[indexPath.row]
.