使用内部对象的实例变量的值对自定义对象的数组进行排序



(很抱歉标题太长)

我有一个自定义对象Person,它又有一个NSSet,它有几个名为Appointment的自定义对象。因此,一个人可以有几个约会。约会的值为startTime和endTime。

这些是核心数据NSMangagedObject类。

@interface Person : NSManagedObject
@property (nonatomic, retain) NSString *personName;
@property (nonatomic, retain) NSSet *appointments;
// etc
@end

@interface Appointment : NSManagedObject
@property (nonatomic, retain) NSNumber * startSecond;
@property (nonatomic, retain) NSNumber * endSecond;
// etc
@end

我如何获得人员列表,按最早开始的顺序在他们的任何约会中排名第二?

您可以使用排序描述符和KVC集合运算符:

NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"appointments.@min.startSecond" ascending:YES];

例如,在CoreData提取中:

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];

或者只是对数组进行排序:

NSArray *people = @[...];
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"appointments.@min.startSecond" ascending:YES];
NSArray *sortedPeople = [people sortedArrayUsingDescriptors:@[sortDescriptor]];

有关KVC采集操作员的更多信息,请参阅《KVC编程指南》。

如果你有NSArray形式的数据,你可以这样排序:

NSArray *sortedPersonArray = [coreDataPersonArray sortedArrayUsingSelector:@selector(compare:)];
- (NSComparisonResult)compare:(Person *)personObject {
    return [self.startSecond compare:personObject.startSecond];
}

建议:

// 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]];
}

最新更新