Skip to main content

NSFetchRequest for all children of a parent



How do I fetch all child entities of a parent?





I have a table populated by a parent entity in Core Data. When the user touches a cell I intend to show another table with all children of that parent.





How does the NSFetchRequest look like for this please?





Edit:





model is like this:







student>>dates [one to many, one student have many days]







So I want all dates for any given student (selected by touching in student table cell for that student), then populate dates table with dates for that student.





Thanks!


Comments

  1. Assuming that the entity and the class names are Student and Date, and the reverse relationship for Date->Student is called student,

    Student *aStudent = ...;
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    [fetchRequest setEntity: [NSEntityDescription entityForName: @"Date" inManagedObjectContext: [aStudent managedObjectContext]]];
    [fetchRequest setPredicate: [NSPredicate predicateWithFormat: @"student == %@", aStudent]];

    ReplyDelete
  2. If you have custom classes, you could traverse the generated relationship (return [student dates]). That will get you an unordered NSSet on iOS4, or, you can do it with a fetch request (note I use ARC so no releases/autoreleases here):

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Date"
    inManagedObjectContext:moc];
    [fetchRequest setEntity:entity];

    NSMutableArray *predicates = [NSMutableArray arrayWithCapacity:3];
    [predicates addObject:[NSPredicate predicateWithFormat:@"student == %@", aStudent]];

    // You might add other predicates
    [fetchRequest setPredicate:[NSCompoundPredicate andPredicateWithSubpredicates:predicates]];

    // and if you want sorted results (why not, get the database to do it for you)
    // sort by date to the top
    NSArray *sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"dateAdded" ascending:NO]];
    }
    [fetchRequest setSortDescriptors:sortDescriptors];

    NSError *error = nil;
    NSArray *sorted = [moc executeFetchRequest:fetchRequest error:&error];
    if (error) {
    // Handle the error, do something useful
    }

    return sorted;

    ReplyDelete
  3. You don't need a separate fetch request for this. All of the objects from the to-many relationship (don't call them child entities, that is misleading and incorrect) are available by accessing the relationship from the student object - something like student.dates. This gives you an NSSet, you can sort it and turn it to an array if you need to.

    ReplyDelete
  4. Within your first table delegate, when you touch a specific cell, I'll inject the specific parent property to the second table controller. For example:

    SecondController secondController = ... // alloc-init
    secondController.studentToGrab = ...


    where SecondController declaration has a studentToGrab property like the following:

    @property (nonatomic, retain) Student* studentToGrab; // use strong with ARC, if non-ARC remember to release it


    and in definition synthesize it.

    Then in your second controller, within viewDidLoad method you could do:

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"YourNameEntityForDate" inManagedObjectContext:self.managedObjectContext];
    [fetchRequest setEntity:entity];

    [fetchRequest setFetchBatchSize:20];

    NSPredicate* predicate = [NSPredicate predicateWithFormat:@"student == %@", studentToGrab];
    [fetchRequest setPredicate:predicate];

    // you can also use a sortdescriptors to order dates...

    NSError *error = nil;
    NSArray *resultArray = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    if (error != nil) {

    NSLog(@"Error: %@", [error localizedDescription]);
    abort();
    }

    // use resultArray to populate something...


    A remark when you deal with table you could also use NSFetchedResultController class. It has advantages when used for displaying data in tables.

    ReplyDelete

Post a Comment

Popular posts from this blog

Why is this Javascript much *slower* than its jQuery equivalent?

I have a HTML list of about 500 items and a "filter" box above it. I started by using jQuery to filter the list when I typed a letter (timing code added later): $('#filter').keyup( function() { var jqStart = (new Date).getTime(); var search = $(this).val().toLowerCase(); var $list = $('ul.ablist > li'); $list.each( function() { if ( $(this).text().toLowerCase().indexOf(search) === -1 ) $(this).hide(); else $(this).show(); } ); console.log('Time: ' + ((new Date).getTime() - jqStart)); } ); However, there was a couple of seconds delay after typing each letter (particularly the first letter). So I thought it may be slightly quicker if I used plain Javascript (I read recently that jQuery's each function is particularly slow). Here's my JS equivalent: document.getElementById('filter').addEventListener( 'keyup', function () { var jsStart = (new Date).getTime()...

Is it possible to have IF statement in an Echo statement in PHP

Thanks in advance. I did look at the other questions/answers that were similar and didn't find exactly what I was looking for. I'm trying to do this, am I on the right path? echo " <div id='tabs-".$match."'> <textarea id='".$match."' name='".$match."'>". if ($COLUMN_NAME === $match) { echo $FIELD_WITH_COLUMN_NAME; } else { } ."</textarea> <script type='text/javascript'> CKEDITOR.replace( '".$match."' ); </script> </div>"; I am getting the following error message in the browser: Parse error: syntax error, unexpected T_IF Please let me know if this is the right way to go about nesting an IF statement inside an echo. Thank you.