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

前端 未结 3 1126
鱼传尺愫
鱼传尺愫 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.

    0 讨论(0)
  • 2021-02-08 07:02

    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]];
    }
    
    0 讨论(0)
  • 2021-02-08 07:11

    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];
    }
    
    0 讨论(0)
提交回复
热议问题