在Swift中使用NSPredicate对CoreData结果进行排序 [英] Sort CoreData results using NSPredicate in Swift

查看:394
本文介绍了在Swift中使用NSPredicate对CoreData结果进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在用Swift编写一个简单的电话簿应用程序,需要对CoreData查询的结果进行排序.

I'm currently writing a simple phone book app in Swift and need to sort the results from a CoreData query.

基本上,我设置了一个名为"Directory"的NSManagedObject,并在-中添加了相应的字段名称. "name_f"是用户的名称.

Basically, I set up an NSManagedObject called "Directory", with the appropriate field names in - e.g. "name_f" is the user's name.

要查询的CoreData数据库中的名称按字母顺序排列.但是,尽管第一次搜索会按字母顺序返回结果,但是在程序的其他区域查询数据库之后,有时可能不会进行进一步的搜索.我不确定为什么会这样,但想输入代码以按任意字段对返回的数组进行有效排序.

The names in the CoreData database that is queried are in alphabetical order. However, although the first search returns the results in alphabetical order, further searches sometimes aren't after the database has been queried by other areas of the program. I'm not sure why this is, but want to put in code to actively sort the returned array by whatever field.

我返回NSManagedObject数组的代码如下:

My code that returns the NSManagedObject array is as follows:

func SearchName(nameToSearch: String) -> NSArray {
    let appDel:AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
    let context:NSManagedObjectContext = appDel.managedObjectContext! //I added the !

    let request = NSFetchRequest(entityName: "Directory")
    request.returnsObjectsAsFaults = false      //will return the instance of the object

    //request.predicate = NSPredicate(format: "name_f = %@", nameToSearch)
    //request.predicate = NSPredicate(format: "name_f MATCHES '.*(\(nameToSearch)).*'")
    request.predicate = NSPredicate(format: "name_f MATCHES[cd] '(\(nameToSearch)).*'")
    var results:NSArray = context.executeFetchRequest(request, error: nil)
    return results
}

顺便说一句,我正在使用以下代码从返回的结果中提取特定值(其中searchResult是SearchName所在类的实例):

As an aside, I'm using the following code to pull a specific value from the returned results (where searchResult is an instance of the class that SearchName is in):

    var particularEntry = self.searchResult[self.selectedItem] as Directory
    lblDetailName.text = thisPerson.name_f

理想情况下,我希望能够: 1-修改上面的代码,以确保对结果"数组进行适当排序. 2-标识随后可应用于结果数组以按任何字段重新排序的代码.

Ideally, I'd like to be able to: 1 - Modify the code above to ensure that the 'results' array is sorted appropriately. 2 - Identify code that could subsequently be applied to the results array to re-sort by any field.

提前谢谢!

推荐答案

感谢-在request.predicate行之前需要以下行:

Thanks - The following lines were required before the request.predicate line:

let sortDescriptor = NSSortDescriptor(key: "name_f", ascending: true)
let sortDescriptors = [sortDescriptor]
request.sortDescriptors = sortDescriptors

这篇关于在Swift中使用NSPredicate对CoreData结果进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆