我有一个表格视图,显示按字母顺序排序的联系人并将其划分为多个部分。
我在用 -
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:[dataSource keyName] ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
对于没有名字的联系人,我使用#号作为他们的第一个字母,因此所有联系人都将被分组。
一切都很棒。我唯一想做的就是将#部分推到表的末尾,因为现在它显示在表的开头。
有任何想法吗?
提前致谢
沙尼
最佳答案
最好的方法是使用sortDescriptorWithKey:ascending:comparator:方法创建自己的自定义排序描述符。这使您可以创建自己的比较功能,可以使用块指定该功能。
首先,创建一个比较函数。如果您以前从未programmed with blocks,现在是时候学习了!
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];
}
};
有了比较功能之后,就可以使用它创建排序描述符了:
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:[dataSource keyName] ascending:YES comparator:myStringComparison];
现在,您可以像使用其他描述符一样使用该排序描述符,并且列表中的#个项目将排在最后!