2013-01-07 99 views
0

我是UISearchBar的新手,我有一些搜索單詞的代碼。如何處理用UISearchBar和UITableView在單詞中搜索單詞?

- (void)searchTableView 
{ 
NSLog(@"Searching..."); 
NSString *searchText = searchBar.text; 

NSMutableArray *tempSearch = [[NSMutableArray alloc] init]; 

for (NSDictionary *item in items) { 

    if ([[item objectForKey:@"en"] isEqualToString:searchText]) { 
     NSLog(@"Found"); 

     [tempSearch addObject:item]; 
    } 
} 

searchArray = [tempSearch copy]; 
} 

它的工作原理,但問題是,它僅適用於完整的詞(例如,如果在UITableViewCelltextLabel是文本「東西」和我類型,然後我有了這個返回行中UISearchBar「東西」,但是當我鍵入「一些」我有行時,完整的單詞是「一些」,「東西」沒有顯示)。我如何搜索文本correclty與我的方法?

回答

1

使用NSPredicate可以簡化您的搜索了一下:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"en BEGINSWITH %@", searchText]; 
NSArray *tempSearch = [items filteredArrayUsingPredicate:predicate]; 

如果你想不區分大小寫的搜索,通過BEGINSWITH[c]更換BEGINSWITH

請參閱Using Predicates在「謂詞編程指南」中獲取更多信息。

0

好吧,我有一些東西,但100%不正確。

for (NSDictionary *item in items) { 

    NSRange range = [[item objectForKey:@"en"] rangeOfString : searchText]; 
    if (range.location != NSNotFound) { 

     NSLog(@"Found"); 

     [tempSearch addObject:item]; 
    } 
} 

當我輸入「E」我有「一些」,「東西」,「其他」 - 我認爲正確的將是當只有「否則」將被退回。

好吧,我已經得到它。

if (range.location != NSNotFound && range.location == 0) {