Sam Burns Sam Burns - 10 months ago 118
iOS Question

sort coreData fetch (swift4)

Right now my code is using NSPredicate or sort descriptor to basically just collect a name. I would like NSPredicate to sort all of the names from a-z thats it.

COREDATAHANDLER

class coreDataHandler: NSObject {

private class func getContext() -> NSManagedObjectContext{

let appDelegate = UIApplication.shared.delegate as! AppDelegate
return appDelegate.persistentContainer.viewContext
}
class func saveObject(username:String, password:String) -> Bool{
let context = getContext()
let entity = NSEntityDescription.entity(forEntityName: "User", in: context)
let managedObject = NSManagedObject(entity: entity!, insertInto: context)

managedObject.setValue(username, forKey: "username")
managedObject.setValue(password, forKey: "password")
do {
try context.save()
return true
} catch {
return false}



}
class func filterData() -> [User]? {
let conttext = getContext()
let fetchRequest:NSFetchRequest<User> = User.fetchRequest()

var user:[User]? = nil

var predicate = NSPredicate(format: "username contains[d] %@" ,"duke")

fetchRequest.predicate = predicate
do {
user = try conttext.fetch(fetchRequest)
return user
}catch {
return user
}
}


VIEWCONTROLLER

user = coreDataHandler.filterData()
for i in user! {
print("Judou : \(i.username!)")
}

Answer Source

If you want your user array to be sorted by username, I would add a class function to your CoreDataHandler class to get a sorted array:

class func getSortedData() -> [User]? {
    let conttext = getContext()
    let fetchRequest:NSFetchRequest<User> = User.fetchRequest()

    var user:[User]? = nil

    var nameSort = NSSortDescriptor(key:"username", ascending:true)

    fetchRequest.sortDescriptors = [nameSort]
    do {
        user = try conttext.fetch(fetchRequest)
        return user
    } catch {
        return user
    }
}

Then in your view controller, use this new function to get the sorted array:

user = coreDataHandler.getSortedData()
for i in user! {
    print("Judou : \(i.username!)")
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download