Sorting array of custom objects using the value of an internal object's instance variable

前端 未结 3 1172
鱼传尺愫
鱼传尺愫 2021-02-08 06:40

(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

3条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-08 06:51

    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.

提交回复
热议问题