Bring certain NSFetchResults to top of list in Swift

67 views Asked by At

I have an iOS app with db of people's names. I also have an array with four of these people's names (varies by user input). I want to show a tableView with all of the entries in the db sorted by alphabet, however I want the four people in the array to appear at the top of the list using the fetch request. I do not want to manipulate the results array directly if at all possible.

Is there a way to do this with sort descriptors? I have tried using the comparator below but had no luck.

var personsInArray: Array<PersonLookup>
let containsComparator: Comparator = {
                (obj1: Any!, obj2: Any!) -> ComparisonResult in
                print("comparing")
                let obj1 = obj1 as! PersonLookup
                let obj2 = obj2 as! PersonLookup
                if personsInArray.contains(obj1) && personsInArray.contains(obj2) {
                    return .orderedSame
                } else if personsInArray.contains(obj1) && !personsInArray.contains(obj2) {
                    return .orderedAscending
                } else if !personsInArray.contains(obj1) && personsInArray.contains(obj2) {
                    return .orderedDescending
                } else {
                    return .orderedSame
                }
            }
            fetchRequest.sortDescriptors? = [NSSortDescriptor(key: "value", ascending: true, comparator: containsComparator), NSSortDescriptor(key: "value", ascending: true)]
0

There are 0 answers