(sorry about the long title)
I have a custom object Person, which in turn has an NSSet
which has several custom objects called Appointment. A Person therefo
You can use sort descriptors and KVC collection operators:
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"appointments.@min.startSecond" ascending:YES];
For example, in a CoreData fetch:
NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Person"];
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"appointments.@min.startSecond" ascending:YES];
[request setSortDescriptors:@[sortDescriptor]];
NSError *error = nil;
NSArray *sortedResults = [context executeFetchRequest:request error:&error];
Or just sorting an array:
NSArray *people = @[...];
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"appointments.@min.startSecond" ascending:YES];
NSArray *sortedPeople = [people sortedArrayUsingDescriptors:@[sortDescriptor]];
More information on KVC collection operators can be found in the KVC Programming Guide.
A suggestion:
// Sorting key
NSString *key = @"startSecond";
// A mutable array version of your list of Persons.
NSMutableArray *a = [NSMutableArray arrayWithObjects:Person1, Person2, Person3, nil];
// Then use the sorted appointements to get your sorted person array.
[a sortUsingComparator:^NSComparisonResult(Person *p1, Person *p2) {
NSSortDescriptor *sortDesc1 = [NSSortDescriptor sortDescriptorWithKey:key ascending:NO];
NSArray *sortedApp1 = [p1.appointements sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDesc1]];
NSSortDescriptor *sortDesc2 = [NSSortDescriptor sortDescriptorWithKey:key ascending:NO];
NSArray *sortedApp2 = [p2.appointements sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDesc2]];
return [[[sortedApp1 objectAtIndex:0] valueForKey:key] compare:[[sortedApp2 objectAtIndex:0] valueForKey:key]];
}
If you have the data in an NSArray form you can sort it like this:
NSArray *sortedPersonArray = [coreDataPersonArray sortedArrayUsingSelector:@selector(compare:)];
- (NSComparisonResult)compare:(Person *)personObject {
return [self.startSecond compare:personObject.startSecond];
}