2015-11-03 64 views
-1

我会通过下面的教程enter link description here需要了解搜索栏

目标C代码和跨越这个代码难倒我它是如何工作的传来:

- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope 
{ 

    // find all the words wich begin with the letter: 

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF beginswith[c] %@", searchText]; 
    // NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"contains[c] %@", searchText]; 
    self.searchResults = [self.array filteredArrayUsingPredicate:predicate]; 
} 






-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString 

    // update the tableview 

{ 


    [self filterContentForSearchText:searchString 


     scope:[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:[self.searchDisplayController.searchBar 


                selectedScopeButtonIndex]]]; 


    return YES; 


} 

我不部分理解是:

scope:[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:[self.searchDisplayController.searchBar selectedScopeButtonIndex]]]; 

这是我的理解,我试图研究它,我知道范围的一个参数。但我现在需要一些解释这个作品。

+1

嗯,你不能孤立地说。你在引用一行。该行是:[self filterContentForSearchText:searchString scope:[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:[self.searchDisplayController.searchBar selectedScopeButtonIndex]]];'你不能孤立地拿一块,并询问它;它本身没有意义。你的问题就像问:“嗨,你好吗?” – matt

回答

0

这是一个复合语句。用这种方式写它会使它更难理解。

我倾向于使用更简单的语句和临时变量,以使代码更容易遵循。 (这也使得调试更加容易,因为你可以在中间步骤之间设置断点并检查这些临时变量。)

原:

[self 
    filterContentForSearchText:searchString 
    scope:[[self.searchDisplayController.searchBar scopeButtonTitles] 
    objectAtIndex: 
    [self.searchDisplayController.searchBar selectedScopeButtonIndex]]]; 

可细分如下:

//Get the search bar's array of button titles 
NSArray *titlesArray = 
    [self.searchDisplayController.searchBar scopeButtonTitles]; 

//Get the index of the selected scope button 
NSInteger index = 
    [self.searchDisplayController.searchBar selectedScopeButtonIndex]; 

//Fetch the string at that index. 

NSString *scopeString = titlesArray[index]; 

//Now assign the string. 
[self 
    filterContentForSearchText: searchString 
    scope: scopeString]; 

看看你是否可以将转换成Swift。如果不回复问题。

(我不熟悉的几个在原来代码中使用。我在调查基础上简单地分析您发布的Objective-C代码是怎么回事一些假设的功能。)