15

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!

Oliver Spencer
  • 2,021
  • 3
  • 16
  • 22
  • Did you have a look at the `sortDescriptors` property of `NSPredicate` ? The "Core Data Programming Guide" has also many examples (in Objective-C), see https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CoreData/Articles/cdFetching.html#//apple_ref/doc/uid/TP40002484-SW1. – Martin R Aug 27 '14 at 18:19
  • sortDescriptors is property of NSFetchRequest. I dont think NSPredicate has such property. – Sandeep Aug 27 '14 at 21:03
  • 1
    @insane-36: You are right, I meant NSFetchRequest. – Martin R Aug 27 '14 at 21:14

2 Answers2

43

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
bwash70
  • 1,135
  • 2
  • 11
  • 24
Oliver Spencer
  • 2,021
  • 3
  • 16
  • 22
  • Or: `request.sortDescriptors = [NSSortDescriptor(key: "name_f", ascending: true)]` if you don't like typing! – Phil R Jan 23 '19 at 13:23
0

I used the above answer from Oliver Spencer, because the sorting approach includes pending changes, which the "max" approach dose not (see apple documentation on NSFetchRequest).

Here my code for convenience:

func fetch_biggestImageID() -> Int {

    print("Fetching biggest ImageID")
    let request: NSFetchRequest<CD_Image> = CD_Image.fetchRequest()
    request.sortDescriptors = [NSSortDescriptor(key: "id", ascending: false)]
    request.fetchLimit = 1

    var maxValue: Int64? = nil
    do {
        let result = try self.managedObjectContext.fetch(request)
        maxValue = result.first?.id
    } catch {
        fatalError("Unresolved error while retrieving max imageID value \(error)")
    }

    return  Int(truncatingIfNeeded:  maxValue ?? 0 )
}
JGS
  • 99
  • 1
  • 5