我正在尝试将UISearchBar添加到我的UITableView。
这是他们用来搜索的方法:
- (void) searchTableView {
NSString *searchText = searchBar.text;
NSMutableArray *searchArray = [[NSMutableArray alloc] init];
for (NSDictionary *dictionary in listOfItems)
{
NSArray *array = [dictionary objectForKey:@"Countries"];
[searchArray addObjectsFromArray:array];
}
for (NSString *sTemp in searchArray)
{
NSRange titleResultsRange = [sTemp rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (titleResultsRange.length > 0)
[copyListOfItems addObject:sTemp];
}
[searchArray release];
searchArray = nil;
}
但是我没有字典,我只想在我的阵列中搜索' exerciseArray'这是这样的初始化:
NSString *path = [[NSBundle mainBundle]pathForResource:@"data" ofType:@"plist"];
NSMutableArray *rootLevel = [[NSMutableArray alloc]initWithContentsOfFile:path];
self.exerciseArray = rootLevel;
[rootLevel release];
当我记录它时,我得到:
exerciseArray: (
{
exerciseName = "Balance Board";
},
{
exerciseName = "Barbell Seated Calf Raise";
},
{
exerciseName = "Calf Press On The Leg Press Machine";
},
{
exerciseName = "Calf Raises- With Bands";
},
那么有人可以帮我修改搜索方法以适应我拥有的数组吗?它似乎有一把钥匙。
我尝试了这个但是它没有工作并在第NSRange titleResultsRange = [sTemp rangeOfString:searchText options:NSCaseInsensitiveSearch];
行
错误*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary rangeOfString:options:]: unrecognized selector sent to instance 0x2d6450
- (void) searchTableView {
NSString *searchText = searchBar.text;
NSLog(@"exerciseArray: %@", exerciseArray);
for (NSString *sTemp in listOfItems)
{
if (sTemp) {
NSRange titleResultsRange = [sTemp rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (titleResultsRange.length > 0)
[copyListOfItems addObject:sTemp];
}
}
}
答案 0 :(得分:0)
看起来你有一个字典数组,每个字典中有一个键/值对(exerciseName)。所以对于你的数据集,应该是这样的:
for (NSDictionary *dictionary in exerciseArray)
{
NSArray *array = [dictionary objectForKey:@"exerciseName"];
[searchArray addObjectsFromArray:array];
}
...
如果您发布与数组相关的VC代码以及tableview数据源方法,我可以修改它并向您展示您需要做什么。
答案 1 :(得分:0)
从表格视图中搜索我已经尝试了这个并且我获得了成功希望它能帮到你......
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
self.searching=NO;
NSString *originalString;
[self.filteredProductArray removeAllObjects];
for (int i=0; i<self.exerciseArray.count; i++)
{
originalString=[[[self.exerciseArray objectAtIndex:i] objectForKey:@"exerciseName"] lowercaseString];
if (!([originalString rangeOfString:[searchText lowercaseString]].location==NSNotFound))
{
[self.filteredProductArray addObject:[self.exerciseArray objectAtIndex:i]];
}
}
if ([searchText isEqual:@""])
{
self.searching=NO;
}
[self.tableView reloadData];
}
答案 2 :(得分:0)
我相信NSPredicates是在数组中搜索的好方法..你可以参考这个链接.. Using NSPredicate to filter an NSArray based on NSDictionary keys