NSSortDescriptor in Swift

前端 未结 7 1647
长情又很酷
长情又很酷 2021-02-02 01:18

I am working on an iOS app and I have data stored in CoreData that I am loading into a UITableView. The data entities have an attribute called id which is a string

7条回答
  •  说谎
    说谎 (楼主)
    2021-02-02 02:00

    Sort descriptors in a (SQLite-based) Core Data fetch request cannot use custom comparators and only a limited set of "built-in" comparison methods. This is documented in Fetch Predicates and Sort Descriptors in the "Core Data Programming Guide":

    ... The SQL store, on the other hand, compiles the predicate and sort descriptors to SQL and evaluates the result in the database itself. This is done primarily for performance, but it means that evaluation happens in a non-Cocoa environment, and so sort descriptors (or predicates) that rely on Cocoa cannot work. The supported sort selectors are compare: and caseInsensitiveCompare:, localizedCompare:, localizedCaseInsensitiveCompare:, and localizedStandardCompare: (the latter is Finder-like sorting, and what most people should use most of the time). In addition you cannot sort on transient properties using the SQLite store.

    Fortunately, there is one that should fit your needs:

    let sortDescriptor = NSSortDescriptor(key: "id", ascending: true,
                           selector: "localizedStandardCompare:")
    

    localizedStandardCompare: does a "Finder-like" comparison and in particular treats digits within strings according to their numerical value.

    For Swift 2.2/Xcode 7.3 and later:

    let sortDescriptor = NSSortDescriptor(key: "id", ascending: true
                             selector: #selector(NSString.localizedStandardCompare))
    

提交回复
热议问题