views:

234

answers:

1

Assumed having the class Account with Name and accountNo both as NSStrings. I want to sort an Array of Accounts either by name or by accountNo. The sort should be done localized.

If I use NSSortDescriptors as described in the Guides I have the option to pass localizedCaseInsensitiveCompare: to the Array, but the numbers are not sorted correctly (100 is sorted before 99). I have not found a way to trigger the option NSNumericSearch for the search. This means I have to use sortedArrayUsingFunctions with a function in every class along the chain. It allows me to sort with correct numerical values but this is not localized and very functional.

If you have answers to both questions (SortDescriptors with Numerically correct sort or sortFunctions with localized and numeric correct sort) please provide me both

Thanks

+1  A: 

You can create a different NSSortDescriptor for each property by which you wish to sort. Each sort descriptor can use a different comparison selector. Your strings can use your localizedCaseInsensitiveCompare: method, and your numbers can use a custom sort selector, something like compareNumeric:.

Then you can just add a category to NSString that defines a method called compareNumeric: that does this:

- (NSComparisonResult) compareNumeric:(id)other {
  return [self compare:other options:NSNumericSearch];
}
Dave DeLong
Hi Dave,sorry for the late answer, I stumbled over this problem now for the second time, I have not really solved it the last time - I just have decided to use only NSNumericSearch because the visibility is higher.Actually your example is not fully matching the requirements: I have strings with both numbers and chars like "123 Max" and "4 Steve". Using the localizedCaseInsensitiveCompare would sort them Max first and Steve second. When using functions the search is correct but not localized.I haven't found a solution yet. But as soon as I have one, I will provide it.Thanks for the answer
maxbareis