核心数据按日期排序对象而不产生预期输出

时间:2018-03-06 09:03:14

标签: cocoa core-data

我正在尝试根据创建对象来显示对象。每个对象都是一个带有dateCreated属性的NSManagedObject。我写了下面的代码:

NSFetchRequest * request = [[NSFetchRequest alloc] init];
NSEntityDescription *e = [NSEntityDescription entityForName:@"MyObject" inManagedObjectContext:context];
request.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"dateCreated" ascending:NO]];
request.entity = e;
NSError * error;
NSArray* result = [context executeFetchRequest:request error:&error];
for (MyObject* object in result) {
     NSLog(@"%@", @([object.dateCreated timeIntervalSince1970]));
}

这是输出:

2018-03-06 08:55:06.591 1520326503.972214
2018-03-06 08:55:06.591 1520326503.995906
2018-03-06 08:55:06.592 1520326504.012891
2018-03-06 08:55:06.592 1520326504.002804
2018-03-06 08:55:06.592 1520326503.989189
2018-03-06 08:55:06.592 1520326504.009239
2018-03-06 08:55:06.592 1520326503.964928
2018-03-06 08:55:06.592 1520326503.968894

即。没有排序。我检查了日期输出是否正确(即按预期),但订单不是。如果我按另一个键(例如名称)排序代码没问题,那么我认为请求是正确设置的。此外,以下代码正确排序结果数组:

result = [result sortedArrayUsingComparator:^NSComparisonResult(MyObject*  _Nonnull obj1, MyObject*  _Nonnull obj2) {
    return [obj2.dateCreated compare:obj1.dateCreated];
}];

0 个答案:

没有答案