0

我有一些数组,其内容是从 db 中选取的。我想将我在“searchTextField”中输入的文本与从 DB 中获取的那些数组的内容相匹配。

例如:我的数组包含,myArray={'bat man','bat and ball','ball'}; 如果我在“searchTextField”中输入了“bat”;它必须在数组中显示匹配文本的索引(在本例中为索引 0 和 1)。

我怎样才能做到这一点..等待你的帮助..

4

1 回答 1

4
NSMutableArray *tempArray = [NSMutableArray arrayWithObjects:@"bat man",@"bat and ball",@"ball", nil];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF contains[c] 'bat'"];
NSArray *result = [tempArray filteredArrayUsingPredicate:predicate];

result数组将包含过滤后的对象,从那里你可以得到索引:

[tempArray indexOfObject:/结果数组中的对象,一一/]

contains[c]意味着搜索将不区分大小写。有关谓词的更多信息:https ://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Predicates/Articles/pUsing.html

编辑

将 textField 的委托设置为 self。在此之前转到 YourFile.h,添加UITextFieldDelegate. 现在textFieldShouldReturn这样做:

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];

    NSMutableArray *tempArray = [NSMutableArray arrayWithObjects:@"bat man",@"bat and ball",@"ball", nil];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF contains[c] %@",textField.text];
    NSArray *result = [tempArray filteredArrayUsingPredicate:predicate];

    return YES;
}
于 2013-02-13T11:25:57.860 回答