How can I sort strings in NSMutableArray into alphabetical order?

后端 未结 4 688
暖寄归人
暖寄归人 2020-12-24 11:26

I have a list of strings in an NSMutableArray, and I want to sort them into alphabetical order before displaying them in my table view.

How can I do tha

相关标签:
4条回答
  • 2020-12-24 11:42

    It's easy to get the ascending order. Follow the bellow steps,,,

    Model 1 :

    NSSortDescriptor *sortDesc = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
    sortedArray=[yourArray sortedArrayUsingDescriptors:@[sortDesc]];
    

    If you want the sorting to be case insensitive, you would need to set the descriptor like this,,
    Model 2 :

    NSSortDescriptor * sortDesc = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES selector:@selector(caseInsensitiveCompare:)]; 
    sortedArray=[yourArray sortedArrayUsingDescriptors:@[sortDesc]];
    
    0 讨论(0)
  • 2020-12-24 11:44

    For me this worked....

    areas = [areas sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
    

    Here areas is NSArray. I hope it helps someone.

    0 讨论(0)
  • 2020-12-24 11:59

    There is the following Apple's working example, using sortedArrayUsingSelector: and localizedCaseInsensitiveCompare: in the Collections Documentation:

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

    Note that this will return a new sorted array. If you want to sort your NSMutableArray in place, then use sortUsingSelector: instead, like so:

    [mutableArray sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
    
    0 讨论(0)
  • 2020-12-24 12:00

    Here's an updated answer for Swift:

    • Sorting can be done in Swift with the help of closures. There are two methods - sort and sorted which facilitate this.

      var unsortedArray = [ "H", "ello", "Wo", "rl", "d"]
      var sortedArray = unsortedArray.sorted { $0.localizedCaseInsensitiveCompare($1) == NSComparisonResult.OrderedAscending }
      

      Note: Here sorted will return a sorted array. The unsortedArray itself will not be sorted.

    • If you want to sort unsortedArray itself, use this

      unsortedArray.sort { $0.localizedCaseInsensitiveCompare($1) == NSComparisonResult.OrderedAscending }
      


    Reference :

    • Here is the documentation for Swift's sorting methods.

    • Docs for different String comparison methods here.


    Optional:

    Instead of using localizedCaseInsensitiveCompare, this could also be done:

    stringArray.sort{ $0.lowercaseString < $1.lowercaseString }
    

    or even

    stringArray.sort{ $0 < $1 }
    

    if you want a case sensitive comparison

    0 讨论(0)
提交回复
热议问题