Search code examples
iosiphonesortingnsarray

Sorting an Array of objects by localized description of a property that contains a number


I have this object that has a property called nameEN that is the name the object has in english. When this object is shown on the screen it is like this:

NSLocalizedStringFromTable([myObject nameEN]);

In other words, the name is localized by using NSLocalizedStringFromTable.

Said that, I have a lot of these objects on an array and I want to sort that array by the localized name.

The problem is that the objects have names like House 1, House 2 ... House 10, etc.

When I sort that using this code:

NSArray *sorted = [unsortedArray sortedArrayUsingComparator:^NSComparisonResult(MyOBject *p1, MyOBject *p2){
NSString *name1 = NSLocalizedStringFromTable([p1 nameEN], @"MyTable", nil);
NSString *name2 = NSLocalizedStringFromTable([p2 nameEN], @"MyTable", nil);
    return [name1 localizedCompare:name2];
  }];

The order I get is House 1, House 10, House 2... 10 before 2, 20 before 3 and so one.

How do I sort this using NSComparisonResult?


Solution

  • Found the answer: just change localizedCompare: with localizedStandardCompare: and it works perfectly.