How to sort a NSArray alphabetically?

前端 未结 7 1184
借酒劲吻你
借酒劲吻你 2020-11-22 15:32

How can I sort an array filled with [UIFont familyNames] into alphabetical order?

7条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 16:23

    The simplest approach is, to provide a sort selector (Apple's documentation for details)

    Objective-C

    sortedArray = [anArray sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
    

    Swift

    let descriptor: NSSortDescriptor = NSSortDescriptor(key: "YourKey", ascending: true, selector: "localizedCaseInsensitiveCompare:")
    let sortedResults: NSArray = temparray.sortedArrayUsingDescriptors([descriptor])
    

    Apple provides several selectors for alphabetic sorting:

    • compare:
    • caseInsensitiveCompare:
    • localizedCompare:
    • localizedCaseInsensitiveCompare:
    • localizedStandardCompare:

    Swift

    var students = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
    students.sort()
    print(students)
    // Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]"
    

    Reference

提交回复
热议问题