.m文件延展声明一个数组变量用于添加搜索的数据签订UISearchBar的代理
@interface TableViewController () <UISearchBarDelegate >
@property (nonatomic , retain) NSMutableArray *arr;
@end
主函数中添加一个UISearchBar对象简单设置
- (void )viewDidLoad {
[super viewDidLoad];
self .arr = @[@"class 1" , @"class 2" , @"class 3" , @"class 4" , @"class 4" , @"lanou" ].mutableCopy ;
UISearchBar *search = [[UISearchBar alloc] initWithFrame:CGRectMake(0 , 100 , 375 , 80 )];
search.delegate = self ;
[self .view addSubview:search];
[search release];
}
调用代理的输入框监视方法
- (void )searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
/**
* 谓词用于if语句的条件和数据筛选
* 通常使用predicateWithFormat:来创建NSPredicate谓词对象
*/
NSPredicate *pred = [NSPredicate predicateWithFormat:@"self contains [cd] %@" , searchText];/**< self 表示要判断包含的对象即下文中的字符串"1234567" [cd]中c表示不区分大小写 d表示不区分低重音 */
BOOL result = [pred evaluateWithObject:@"1234567" ];
NSMutableArray *arr = [NSMutableArray arrayWithCapacity:0 ];
for (NSInteger i = 0 ; i < self.arr.count; i++) {
NSString *text = [self.arr objectAtIndex:i];
if ([pred evaluateWithObject:text]) {
[arr addObject:text];
}
}
NSLog(@"%@" , arr);
}
注1 : 谓词的常用语法判定条件
BEGINSWITH(以... 开始)
The left-hand expression begins with the right-hand expression.
/* 注意:简单举例
* 字符串1234567 包含 1 , 2 , 123 但不包含13 , 14 , 16
*/
本文中使用的是CONTAINS(包含)
The left-hand expression contains the right-hand expression.
ENDSWITH(以... 结束)
The left-hand expression ends with the right-hand expression.
LIKE(是... )
The left hand expression equals the right-hand expression: ? and * are allowed as wildcard characters, where ? matches 1 character and * matches 0 or more characters.
谓词还可以进行大量的判断包括(=, >=, <=, all等判断),详见官方API中Predicate Format String Syntax(谓词语法介绍)
注2 : UITableViewController作为根视图省去写代理和实现代理方法的过程
- (NSInteger )numberOfSectionsInTableView:(UITableView *)tableView {
return 1 ;
}
- (NSInteger )tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger )section {
return self .arr .count ;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"cell" ;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
cell = [[[UITableViewCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:CellIdentifier] autorelease];
}
cell.textLabel .text = [self .arr objectAtIndex:indexPath.row ];
return cell;
}
内存管理
- (void)dealloc {
[_arr release];
[super dealloc];
}