问题描述
我有一个表格视图,显示按字母顺序排序的联系人,并将其划分为部分。
I have a table view that shows contacts sorted by alphabetic ordering and divide it to sections.
我正在使用 -
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:[dataSource keyName] ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
然后对于没有姓名的联系人我使用#符号作为他们的第一个字母,所以所有这些都将被分组在一个小组中。
then for contacts without name i am using # sign as their first letter so all of them will be grouped in one group.
一切都很棒。我唯一想要的就是将#部分推到表的末尾,就像现在它显示在它的开头一样。
everything is great. the only thing i want is to push the # section to the end of the table, as for now it shows in the beginning of it.
任何想法?
提前感谢
shani
推荐答案
执行此操作的最佳方法是使用sortDescriptorWithKey:ascending:comparator:方法创建自己的自定义排序描述符。这使您可以创建自己的比较函数,使用块指定。
The best way to do this is to create your own custom sort descriptor using the sortDescriptorWithKey:ascending:comparator: method. This lets you create your own comparison function, which you specify using a block.
首先,创建一个比较函数。如果您之前从未是时候学习了!
First, create a comparison function. If you've never programmed with blocks before, now is the time to learn!
NSComparisonResult (^myStringComparison)(id obj1, id obj2) = ^NSComparisonResult(id obj1, id obj2) {
// Get the first character of the strings you're comparing
char obj1FirstChar = [obj1 characterAtIndex:0];
char obj2FirstChar = [obj2 characterAtIndex:0];
// Check if one (but not both) strings starts with a '#', and if so, make sure that one is sorted below the other
if (obj1FirstChar == '#' && obj2FirstChar != '#') {
return NSOrderedDescending;
} else if (obj2FirstChar == '#' && obj1FirstChar != '#') {
return NSOrderedAscending;
}
// Otherwise return the default sorting order
else {
return [obj1 compare:obj2 options:0];
}
};
现在您已经拥有了比较功能,您可以使用它来创建排序描述符:
Now that you have your comparison function, you can use it to create a sort descriptor:
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:[dataSource keyName] ascending:YES comparator:myStringComparison];
您现在可以像使用其他任何一样使用该排序描述符,并且您的列表将具有#物品排序到最后!
You can now use that sort descriptor just like you would any other, and your list will have the # items sorted to the end!
这篇关于NSSortDescriptor - 将#和数字推到列表的末尾 - iphone xcode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!