0

我的 CoreData 数据库中有一个对象,这些对象具有 NSDate 类型的“日期”属性。如何获取 10 个最早日期的对象?

这是我到目前为止所拥有的:

NSFetchRequest *fetchRequest = [NSFetchRequest new];
fetchRequest.entity = [NSEntityDescription entityForName:NSStringFromClass([MyManagedObject class]) inManagedObjectContext:self.database.managedObjectContext];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"date" ascending:YES];
[fetchRequest setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];
NSArray *result = [self.database.managedObjectContext executeFetchRequest: fetchRequest error: nil];

我相信这将使我所有的托管对象按排序顺序返回,但我真的只需要 10 个最新的对象。我怎样才能做到这一点?NSFetchRequest使用 a 对它们进行排序而不是全部获取它们然后以编程方式对它们进行排序会更快吗?

4

2 回答 2

6

按降序对记录进行排序,我们fetchLimit只得到最近的结果:

NSFetchRequest *fetchRequest = [NSFetchRequest new];
fetchRequest.entity = [NSEntityDescription entityForName:NSStringFromClass([MyManagedObject class]) 
                                  inManagedObjectContext:self.database.managedObjectContext];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"date" 
                                                               ascending:NO];
[fetchRequest setSortDescriptors:@[sortDescriptor]];
[fetchRequest setFetchLimit:10];
NSArray *result = [self.database.managedObjectContext executeFetchRequest:fetchRequest 
                                                                    error:nil];
于 2013-04-09T22:08:25.960 回答
0
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"date" ascending:NO];
...
NSArray* tenSoonestElements = [result subarrayWithRange:NSMakeRange(0, 10)];
于 2013-04-09T22:08:03.640 回答