我在 sqlite 中使用语句从表中选择特定对象:
NSString *statment = [NSString stringWithFormat:@"SELECT * FROM %@ ORDER BY %@ DESC LIMIT 1", TRAP_TABLE, DISTANCE_TO_CLOSE_POINT];
我想使用核心数据做同样的事情。
我应该如何混合使用 NSPredicate
和 NSSortDescriptor
才能达到同样的效果?
编辑: 这是我所做的,还没有尝试过:
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:DISTANCE_TO_CLOSE_POINT ascending:NO selector:@selector(localizedCompare:)];
最佳答案
NSPredicate
就像 SQL 语句的 where 子句。您的示例没有 where 子句。
在 NSFetchRequest
中,您可以添加排序描述符来处理“排序依据”。同样在 NSFetchRequest
中,您可以设置获取限制。
从那里您将 NSFetchRequest
传递给 NSManagedObjectContext
并接收您的结果。
更新1
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:DISTANCE_TO_CLOSE_POINT ascending:NO selector:@selector(localizedCompare:)];
在这种情况下,这太过分了。我猜你排序的值是一个数字,这意味着你不需要 localizedCompare:
因为你没有使用字符串。所以你可以将其简化为:
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:DISTANCE_TO_CLOSE_POINT ascending:NO];
如果您在 ARC 项目中,甚至可以将其缩减为:
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:DISTANCE_TO_CLOSE_POINT ascending:NO];
然后可以将其直接扔进 NSFetchRequest
:
[fetchRequest setSortDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:DISTANCE_TO_CLOSE_POINT ascending:NO]]];
关于ios - 将 Core Data 语句等同于 SQLite 语句(按 ... desc.. 排序),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21634220/