Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6871257
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T03:46:59+00:00 2026-05-27T03:46:59+00:00

I am a noob when it comes to traversing Core Data many-to-many relationships (I

  • 0

I am a noob when it comes to traversing Core Data many-to-many relationships (I have read numerous threads and documentation on this so unless it’s and end all, please no links to documentation or threads).

I am making an inventory application and currently have a Core Data model that includes an “Thing”, “Category”, “Location”, and “ThingLocation” (ThingLocation is an entity that holds both a Thing and Location reference but includes the amount of Things on that particular Location. Also a many-to-many relationship) Entities that I would like to populate my UI with. I am proficient in GUI so this is not a question of User Interface but rather how I would gather the information using (probably) NSPredicates.

Ex: If I show a TableView consisting of a Category entity’s details then how would I populate it with the Things in that Category Entity.

Ex: If I wanted to display a UILabel showing the total amount of Thing‘s there were in it. (i.e. add up all of the amounts on each Location).

EDIT: I want to be able to use an NSFetchedResultsController!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-27T03:46:59+00:00Added an answer on May 27, 2026 at 3:46 am

    I am not exactly sure what your question is asking. So for example you want to iterate over all the categories and all the things in that category you would first do a request for the entities of category without a predicate (this will return all category objects) and iterate over all those with fast enumeration:

    //iOS 5 way of doing it
    NSFetchRequest* request = [NSFetchRequest fetchRequestWithEntity:@"Category"];
    NSArray* arrayOfObjects = [context executeFetchRequest: request withError: nil];
    for (Category* cat in arrayOfObjects)
    {
        //iterate over all the things in that category
        for (Thing* thing in cat.things){
        {
            //do something?
        }
    }
    

    For your first example of populating a tableview with things in a category,

    If you have the category you would get the Things very easily like this:

    NSSet* things= category.things;
    //you can get it into an array by sorting it somehow or just get it like that.
    NSMutableArray* things = [[category.things allObjects] mutableCopy];
    

    You can iterate over this in a very normal fashion or use them as your datasource for your tableview. If you don’t have the category you need something to distinguish it in which case you would set up the predicate like this:

    NSFetchRequest* request = [NSFetchRequest fetchRequestWithEntity:@"Thing"];
    NSPredicate* pred = [NSPredicate predicateWithFormat:@"(relationToCat.DestAtt = %@)",howToDestinguish];
    

    This will return all the Things that are connected to a category that has that attribute.

    For your second example, You would set the NSPredicate up to get all the ThingLocations for that specific Thing. Then iterate over them and add up the values at the locations. If you wanted to do this for every category over everything it would just require you to nest some for loop starting with the categories. then for each thing get all the ThingLocations and for each of those add up the values.

    I hope that answers your questions. To-Many relations are just sets and can be treated as such. I find that thinking from the bottom up helps me form the predicates. thinking I need all the things in this category so I would set up with the entity of Things and connecting it back to the category in the predicate.

    Edit: NSFetchedResultsController example
    In your .h file after declaring your super class add NSFetchedResultsControllerDelegate to the delegates implemented.

    Create an ivar:
    @property (nonatomic, retain) NSFetchedResultsController* fetchedResultsController;

    On the implementation side I’ve seen two different approaches, the first is writing a custom accessor for the property that initializes it there, the other is just to do it in the viewDidLoad in either case the setup is as follows:

    NSFetchRequest *fetchRequest = [[[NSFetchRequest alloc] init] autorelease];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Thing" inManagedObjectContext:context];
    NSPredicate* pred=[NSPredicate predicateWithFormat:@"(relToCat.something=%@)",something];
    [fetchRequest setPredicate:pred];
    [fetchRequest setEntity:entity];
    [fetchRequest setFetchBatchSize:20]; //tells it how many objects you want returned at a time.
    
    //this is for displaying the things in some sort of order. If you have a name attribute you'd do something like this
    NSSortDescriptor *descriptor = [[[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES] autorelease];
    NSArray *sortDescriptors = [[[NSArray alloc] initWithObjects: descriptor, nil] autorelease];
    [fetchRequest setSortDescriptors:sortDescriptors];
    
    //this is the set up. If you put a sectionNameKeyPath it will split the results into sections with distinct values for that attribute
    NSFetchedResultsController *frc = nil;
    frc = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:context] sectionNameKeyPath:@"attribute that splits it into sections" cacheName:nil];
    [frc setDelegate:self];
    [self setFetchedResultsController:frc];
    [frc release];
    frc = nil;
    
    //Tells it to start.
    [fetchedResultsController performFetch:nil];
    

    Then for the table view delegate methods it is a piece of cake like so:

    -(NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    
        return [[[fetchedResultsController sections] objectAtIndex:section] name];
    }
    - (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView {
            return [[fetchedResultsController sections] count];
    }
    - (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section
    {
            return [[[fetchedResultsController sections] objectAtIndex: section] numberOfObjects];
    }
    /* If you want the bar on the right with the names of the sections...
    -(NSArray*) sectionIndexTitlesForTableView:(UITableView *)tableView{
        return [fetchedResultsController sectionIndexTitles];
    }*/
    -(UITableViewCell* )tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
            static NSString* ident=@"cellident";
        UITableViewCell *cell = [self.itemTable dequeueReusableCellWithIdentifier:ident]; 
        if (!cell) {
            cell = [[[UITableViewCell alloc] initWithStyle: UITableViewCellStyleDefault reuseIdentifier:ident] autorelease];
        }
        [self configureCell:cell atIndexPath:indexPath];
        return cell;
    }
    - (void) configureCell:(UITableViewCell*)cell atIndexPath:(NSIndexPath*)indexPath {
        NSManagedObject* item=[fetchedResultsController objectAtIndexPath:indexPath];
        //set up your cell somehow
        return cell;
    }
    

    You also need to add the delegate methods for the fetched results controller. They are all very simple and look something like this:

    - (void)controllerWillChangeContent:(NSFetchedResultsController*)controller {
        [tableView beginUpdates];
    }
    - (void)controller:(NSFetchedResultsController*) controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type
    {
        NSIndexSet *set = [NSIndexSet indexSetWithIndex:sectionIndex];
        switch(type) {
            case NSFetchedResultsChangeInsert: [tableView insertSections:set  withRowAnimation:UITableViewRowAnimationFade];
                break;
            case NSFetchedResultsChangeDelete:
                [tableView deleteSections:set withRowAnimation:UITableViewRowAnimationFade];
                break;
        }
    }
    - (void)controller:(NSFetchedResultsController*)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath*)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath*)newIndexPath
    {
        UITableView *tv = tableView;
        switch(type) {
            case NSFetchedResultsChangeInsert:
                [tv insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
    
                break;
            case NSFetchedResultsChangeDelete:
                [tv deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    
                break;
            case NSFetchedResultsChangeUpdate:
                [self configureCell:[tv cellForRowAtIndexPath:indexPath] atIndexPath:indexPath];
                break;
            case NSFetchedResultsChangeMove:
                [tv deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
                [tv insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
                break;
        }
    
    }
    - (void)controllerDidChangeContent:(NSFetchedResultsController*)controller {
        [tableView endUpdates];
    }
    

    This will update the table if in some other part of the program a thing is added it will automatically show up on the table if the predicate matches.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I guess this is a noob question, but here it comes: I have a
I am a complete Noob when it comes to GIT. I have been just
I'm a total noob when it comes to C but i found this curl
I'm a total noob when it comes to iPhone development and have been tasked
I am a complete noob when it comes to the NoSQL movement. I have
Hey i am a noob when it comes to php because i have just
I am super noob when comes to javascipt, how come click() isn't working? This
I am a noob when it comes to SQL syntax. I have a table
I am kinda a noob when it comes to interacting with servers. I have
I am a noob when it comes to python. I have a python script

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.