简体   繁体   English

核心数据中的升序排序

[英]Ascending Sort in Core Data

I want to fetch Objects in Ascending order from core data. 我想从核心数据中按升序获取对象。 The problem is, I want the objects as 问题是,我希望对象

Abc ,abc Ball, ball bat, Cat, can

But, it sends like, 但是,它发送像

Abc,Ball,Cat ,abc, ball, cat

Following is my code. 以下是我的代码。

class func CD_FetchAllContacts()->[RecentContact]{
    var arrResult:[RecentContact] = []
    let managedContext = PM.instance().managedObjectContext
    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "RecentContact")
   fetchRequest.sortDescriptors = [NSSortDescriptor(key: "firstName", ascending: true, selector: #selector(NSString.caseInsensitiveCompare))]
    do {
        let results =
            try managedContext?.fetch(fetchRequest)
        arrResult = results as! [RecentContact]
    } catch let error as NSError {
        print("Could not fetch \(error), \(error.userInfo)")
    }
    print(arrResult.count)
     return arrResult
}

The sort descriptor should be like this, with (_ :) at the end: 排序描述符应该是这样的,结尾是(_ :)

fetchRequest.sortDescriptors = [NSSortDescriptor(key: "firstName", ascending: true, selector: #selector(NSString.caseInsensitiveCompare(_:)))]

Edit: Actually even with your version of the sort descriptor it's working on a test project I've done. 编辑:实际上,即使使用您的排序描述符版本,它也可以在我已经完成的测试项目中工作。 Nothing seems wrong with the code posted. 发布的代码似乎没有错。 Are you sorting the returned array in other part of your code? 您是否在代码的其他部分对返回的数组进行排序?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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