[英]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. 我有一个具有名为
nameEN
的属性的对象,该属性是该对象在英语中的名称。 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
. 换句话说,使用
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. 问题在于对象的名称类似于
House 1
, House 2
... House 10
等。
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. 我得到的顺序是
House 1
号House 10
号House 2
... 2之前的10、3号之前的20等。
How do I sort this using NSComparisonResult
? 如何使用
NSComparisonResult
对此进行排序?
找到了答案:只要改变localizedCompare:
与localizedStandardCompare:
和它完美的作品。
Try finding last whitespace with rangeOfCharacter method with NSBackwardsSearch option enabled. 尝试使用启用了NSBackwardsSearch选项的rangeOfCharacter方法查找最后一个空格。 With this range you can divide your string and compare first part containing name separately from second part containing number.
在此范围内,您可以分割字符串并分别比较包含名称的第一部分和包含数字的第二部分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.