Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort CoreData results using NSPredicate in Swift

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

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

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.

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
}

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

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.

Thanks in advance!

like image 886
Oliver Spencer Avatar asked Aug 27 '14 18:08

Oliver Spencer


1 Answers

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
like image 93
Oliver Spencer Avatar answered Oct 20 '22 10:10

Oliver Spencer