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

前端 未结 3 1131
鱼传尺愫
鱼传尺愫 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 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]];
    }
    

提交回复
热议问题