简体   繁体   中英

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 ?

找到了答案:只要改变localizedCompare:localizedStandardCompare:和它完美的作品。

Try finding last whitespace with rangeOfCharacter method with NSBackwardsSearch option enabled. With this range you can divide your string and compare first part containing name separately from second part containing number.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM