简体   繁体   中英

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 az 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!)")
    }

If you want your user array to be sorted by username and then password , 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)            
    var passwordSort = NSSortDescriptor(key:"password", ascending:false) 

    fetchRequest.sortDescriptors = [nameSort, passwordSort]
    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!), Password:\(i.password)")
}

In swift 4 or swift 5, you can use

func sortlist(){

    //1
    guard let appDelegate =
        UIApplication.shared.delegate as? AppDelegate else {
            return
    }

    let managedContext =
        appDelegate.persistentContainer.viewContext

    //2
    let fetchRequest =
        NSFetchRequest<NSManagedObject>(entityName: "User")
    let sort = NSSortDescriptor(key: "username", ascending: false)
    fetchRequest.sortDescriptors = [sort]

    //3
    do {
        let  langugeCodes = try managedContext.fetch(fetchRequest)
        for result in langugeCodes as [NSManagedObject] {
            var   username:String = result.value(forKey: "username")! as! String
            var   password:String = result.value(forKey: "password")! as! String

            print("username==>",username)
            print("name==>",name)

        }


    } catch let error as NSError {
        print("Could not fetch. \(error), \(error.userInfo)")
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM