2010-04-22 47 views
1

我有一個UITableView,包含我想按第一個字母(類似於地址簿應用程序)分組(排序)的名稱。我目前能夠搭配任何部分( 'A' - 'Z')使用:可可觸摸UITableView按字母順序排列'#'全部匹配無匹配

// Sections is an array of strings "{search}" and "A" to "Z" and "#". 
NSString *pattern = [self.sections objectAtIndex:section]; 
NSPredicate *predicate = nil; 

// Ignore search pattern. 
if ([pattern isEqualToString:@"{search}"]) return nil; 

// Non-Alpha and Non-Diacritic-Alpha (?). 
if ([pattern isEqualToString:@"#"]); 

// Default case (use case and diacritic insensitivity). 
if (!predicate) predicate = [NSPredicate predicateWithFormat:@"name beginswith[cd] %@", pattern]; 

// Return filtered results. 
return [self.friends filteredArrayUsingPredicate:predicate]; 

然而,對於 '#' 匹配我摸不透。我試着用構建一個正則表達式匹配:

[NSPredicate predicateWithFormat:@"name matches '[^a-zA-Z].*'"]; 

但失敗了變音-α(重複行出現)。任何想法將不勝感激!謝謝。

回答

6

我通常使用UILocalizedIndexedCollation和一個自定義的NSArray類來處理這個問題。我還有一個UILocalizedIndexedCollat​​ion的包裝器(裝飾器),它將包含搜索符號併爲您處理偏移量。

NSArray類的實現是在這裏:http://gist.github.com/375409

因此,考慮用name屬性的對象objects的數組,我想創建一個索引數組,像這樣:

UILocalizedIndexedCollation *collation = [UILocalizedIndexedCollation currentCollation]; 
NSArray *indexedObjects = [objects indexUsingCollation:collation withSelector:@selector(name)]; // returns an array of arrays 

及其重要請注意0​​已經處理了以本地化方式對您的對象進行索引和分組的邏輯,因此不需要在此重新發明輪子。

我的排序裝飾工具處理搜索圖標可以在this github gist找到。

使用它的更詳細的教程可以找到on my blog

在這種情況下,您只需在上面的示例中傳入我的整理包裝的實例而不是UILocalizedIndexedCollat​​ion。

+0

感謝您的快速回復盧克!我現在只是看看現在的一切,並做了修復,看看它是否工作!乾杯。 – 2010-04-22 16:05:21