2012-08-12 41 views
0

我有以下行来排序和节我的tableview。iOS:如何使用整数值对我的表格视图进行排序,但希望显示字符串值?

NSSortDescriptor *sortDescriptorState = [[NSSortDescriptor alloc] initWithKey:@"positionSort" ascending:YES]; 

以上是一个整数值,它根据各自的positionSort值对我的单元格进行排序。 我也有下面的代码来显示部分名称;但是,这些部分仍按字母顺序排列,而不是按照排序顺序排列。我该如何解决这个问题?

NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:@"position" cacheName:@"Master"]; 

谢谢!

更新:感谢@MartinR我能够得出答案。

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { 

    id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section]; 

    // Here I build up one of my Position objects using my unique position passed. 
    // I had to cast the object as NSMutableString* to get rid of a warning 
    Position * aPosition = [Position positionWithUniquePosition:(NSMutableString *)[[[sectionInfo objects] objectAtIndex: 0] position] 
             inManagedObjectContext:self.managedObjectContext]; 

    // Once the above is done then I simply just accessed the attribute from my object 
    return aPosition.positionDescription; 

} 
+0

我不认为你已经够张贴在这里继续下去。我做了很像这样的事情,它从来没有造成任何问题。 – 2012-08-12 16:06:13

+0

'positionSort'是一个Integer属性还是一个字符串属性,它包含整数作为字符串? - 请记住,如果对排序描述符和“sectionNameKeyPath”使用不同的键,则两个键必须生成相同的相对排序。 – 2012-08-12 17:58:49

+0

@MartinR是的,他们是不同的。 positionSort(即:1,21,22,40等)和位置(即经理,职员等)。所以基本上我试图让字幕(位置)以非字母顺序显示。这就是为什么我有了posSort。 – daveomcd 2012-08-13 00:56:15

回答

1

initWithFetchRequest:managedObjectContext:sectionNameKeyPath:cacheName:文档:

sectionNameKeyPath

...如果这个 关键路径是不一样的,通过在fetchRequest第一个排序 描述符中规定,它们必须产生相同的相关 排序。例如,fetchRequest 中的第一个排序描述符可以指定持久属性的关键字; sectionNameKeyPath 可能会为持久属性的 派生的瞬态属性指定密钥。

所以你不能在sectionNameKeyPath使用排序描述符“positionSort”和“位置”,因为排序数字和字符串进行排序不会产生相同的相对排序。

我会对两者使用“positionSort”,并更改tableView:titleForHeaderInSection:,以便它返回位置名称作为部分标题而不是位置编号。

我没有这个尝试自己,但这样的事情应该工作:

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { 
    id <NSFetchedResultsSectionInfo> sectionInfo = [[self.controller sections] objectAtIndex:section]; 
    return [[[sectionInfo objects] objectAtIndex:0] position]; 
} 
+0

谢谢这是一个很大的帮助。我将把这个答案引导到我的问题中作为更新 - 也许这对其他人有用。 – daveomcd 2012-08-13 14:46:41

相关问题