以下是使用NSSortDescriptor
的示例用法,其结果与sortedByFirstNameSwifty
相同,那么Swift中需要NSSortDescriptor
吗?
class Person: NSObject {
let firstName: String
let lastName: String
let age: Int
init(firstName: String, lastName: String, age: Int) {
self.firstName = firstName
self.lastName = lastName
self.age = age
}
override var description: String {
return "\(firstName) \(lastName)"
}
}
let a = Person(firstName: "a", lastName: "b", age: 24)
let b = Person(firstName: "c", lastName: "d", age: 27)
let c = Person(firstName: "e", lastName: "f", age: 33)
let d = Person(firstName: "g", lastName: "h", age: 31)
let peopleObject = [d, b, a, c]
//SWIFTY
let sortedByFirstNameSwifty = peopleObject.sorted(by: { $0.firstName < $1.firstName })
print(sortedByFirstNameSwifty)//prints[a b, c d, e f, g h]
//Objective c way
let firstNameSortDescriptor = NSSortDescriptor(key: "firstName", ascending: true, selector: #selector(NSString.localizedStandardCompare(_:)))
let sortedByFirstName = (peopleObject as NSArray).sortedArray(using: [firstNameSortDescriptor])
print(sortedByFirstName)//prints [a b, c d, e f, g h]
答案 0 :(得分:3)
NSSortDescriptor的优点是你可以使用它们的数组进行排序,如果两个对象根据第一个描述符变得相等,那么你可以回退到第二个描述符来对它们进行排序。
例如,假设您按修改日期对多个文件进行了排序。如果两个文件碰巧具有完全相同的修改日期,您可能希望按名称对这两个文件进行排序。因此,您将使用排序描述符数组,第一个按日期排序,第二个按文件名排序。