【问题标题】:Sort Core Data attributes both by Date and Character按日期和字符对核心数据属性进行排序
【发布时间】:2016-07-21 18:56:52
【问题描述】:

我正在尝试搜索我的核心数据,默认情况下它搜索标题属性,但我还需要按 date 对结果进行排序。

我的代码搜索 title 属性,但我怎样才能创建两个 predicates 并将它们与 context 连接起来?

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

    let currentText = textField.text ?? ""
    let prospectiveText = (currentText as NSString).stringByReplacingCharactersInRange(range, withString: string)

    //Load data from Core Data
    let appDel : AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    context =  appDel.managedObjectContext

    do {

        request =  NSFetchRequest(entityName: "Event")
        let sort:NSSortDescriptor = NSSortDescriptor(key:"title", ascending: true)
        request.sortDescriptors = [sort]
        let searchPredicate = NSPredicate(format: "title CONTAINS[c] %@", prospectiveText)
        request.predicate = searchPredicate
        results = try context.executeFetchRequest(request)

        animateTableCell()


    } catch {

        print("ERROR")
    }

    return true;
}

【问题讨论】:

    标签: ios iphone swift xcode core-data


    【解决方案1】:

    不清楚您是否对选择排序感兴趣。谓词用于确定选择哪些记录,排序描述符用于对结果进行排序。

    对于排序,request.sortDescriptors 是一个描述符数组。所以你可以有多个描述符,例如:

    let sort:NSSortDescriptor = NSSortDescriptor(key:"title", ascending: true)
    let sort2:NSSortDescriptor = NSSortDescriptor(key:"date", ascending: false)
    request.sortDescriptors = [sort, sort2]
    

    应按标题升序排序,然后是日期降序(即具有相同标题的项目应按日期降序排列)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-08
      相关资源
      最近更新 更多