1
votes

I have a Core Data object called Workshop. It has a to-many relationship to Student objects.

How would I get an NSArray of Student surnames (surname being an NSString property of Student) from the Workshop object? Preferably in alphabetical order?

1

1 Answers

2
votes

Warning: Untested Code Incoming

Assuming both your Workshop and Student entities have a "name" attribute and your student entity has a relationship called "Workshop" this is how you would fetch the objects:

- (NSArray*) getStudentsForWorkshop:(NSString*) workshopName {
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];   
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Student" 
                                          inManagedObjectContext:managedObjectContext];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"Workshop.name LIKE %@", workshopName];
    [fetchRequest setPredicate:predicate];
    [fetchRequest setEntity:entity];                                         

    NSArray *result = [managedObjectContext executeFetchRequest:fetchRequest error:nil]];

    NSArray *sortedArray = [NSArray arrayWithArray: [result sortedArrayUsingSelector:@selector(compareStudent:)]];
    return sortedArray;      
}

For sorting you would implement compareStudent like so:

- (NSComparisonResult)compareStudent:(NSManagedObject*)otherObject {
    return [self.name compare:otherObject];
}