【问题标题】:Equal Core Data statement to SQLite statement (order by ... desc..)与 SQLite 语句相等的 Core Data 语句(按 ... desc.. 排序)
【发布时间】:2014-02-07 17:33:59
【问题描述】:

我正在使用 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:)];

【问题讨论】:

    标签: ios objective-c sqlite core-data


    【解决方案1】:

    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]]];
    

    【讨论】:

    • 最终我做到了: NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:DISTANCE_TO_CLOSE_POINT 升序:没有选择器:@selector(localizedCompare:)]; ,不知道行不行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-25
    • 1970-01-01
    • 2021-08-14
    • 1970-01-01
    • 2014-11-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多