如何按整数属性对 CoreData 对象的数组进行排序



我有一个 CoreData 对象的数组,每个对象都是Person的,每个Person都有一个 Integer32 类型的 age 属性。

我的数组充满了Person对象。我想按数组的age属性对数组进行排序。

我该怎么做?

它应该像这样简单:

NSArray *sortDescriptors = @[
  [NSSortDescriptor sortDescriptorWithKey:@"age" ascending:YES]
];
NSArray *sortedPeople = [people sortedArrayUsingDescriptors:sortDescriptors];
NSLog(@"%@", sortedPeople);

无论您在创建NSManagedObject子类时是否选择"对基元数据类型使用标量属性"(如果您决定创建它们),这都将起作用

假设"人员"是您想要排序的 Person 对象数组......

NSArray *sortedPeople = [people sortedArrayUsingComparator:^NSComparisonResult(Person *p1, Person *p2) {
    if (p1.age > p2.age) return NSOrderedDescending;
    else if (p1.age < p2.age) return NSOrderedAscending;
    else return NSOrderedSame;
}

最新更新