2012-08-12 45 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

相關問題