ios - 将 Core Data 语句等同于 SQLite 语句(按 ... desc.. 排序)

标签 ios objective-c sqlite core-data

我在 sqlite 中使用语句从表中选择特定对象:

 NSString *statment = [NSString stringWithFormat:@"SELECT * FROM %@ ORDER BY %@ DESC LIMIT 1", TRAP_TABLE, DISTANCE_TO_CLOSE_POINT];

我想使用核心数据做同样的事情。 我应该如何混合使用 NSPredicateNSSortDescriptor 才能达到同样的效果?

编辑: 这是我所做的,还没有尝试过:

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/

相关文章:

ios - 如何包含位于不同组中的 Swift 文件?

objective-c - 使用空类作为数据类型

python - SQLite 数据库查询(Python、Bottle)

ios - 将文件保存到 icloud 驱动器

ios - 在同一个按钮中多次展开 - Swift

ios - 如何初始化 NSString 的 NSArray?

ios - UITableView 滚动时改变 UIView 的高度

php - SQL JOIN有条件地包含多行

android - 获取 SQLite 中列的类型

ios - 如何仅在 ScrollView 中禁用滚动而不在内容 View 中禁用滚动?