Getting NSFetchedResultsController, NSSortDescription and sectionNameForKeyPath to work together

后端 未结 4 1766
陌清茗
陌清茗 2021-01-18 02:23

I\'m currently working on an App that has a couple of Entities and relationships as illustrated below:

Item <<--> Category.

4条回答
  •  攒了一身酷
    2021-01-18 02:50

    Why are you fetching Item and not Category? If I understand your relationships correctly, Category owns a 1 to many relationship with Item, so in theory a Category instance should have an 'items' property that returns every Item in that category.

    If that's the case, then you could simply fetch all of your categories, and then sort them by displayOrder. Then, forget about using sections in the NSFetchedResultsController itself. Instead, your associated tableView methods would look something like:

    - (NSInteger)numberOfSections {
        return [[self.fetchedResultsController fetchedObjects] count];
    }
    
    - (NSInteger)numberOfRowsInSection:(NSInteger)section {
        Category* category = [[self.fetchedResultsController fetchedObjects] objectAtIndex:section];
        return [[category items] count];
    }
    
    - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
        Category* category = [[self.fetchedResultsController fetchedObjects] objectAtIndex:section];
        return category.name;
    } 
    

    In short, I think you are overcomplicating things by fetching Item instead of Category, and by trying to make the NSFetchedResultsController manage your section grouping for you. It is much simpler and requires much less code to just do the section management yourself.

提交回复
热议问题