我有一个解析iOS应用程序,我需要搜索几千个用户的名字(~3,000)。我正在尝试修改我的搜索代码,以便我可以这样做,但我需要帮助。现在我的搜索代码如下所示:
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (tableView == self.tableView) {
return self.objects.count;
} else {
return self.searchResults.count;
}
}
-(void)filterResults:(NSString *)searchTerm :(int)limit :(int)skip {
[self.searchResults removeAllObjects];
PFQuery *query = [PFQuery queryWithClassName:@"_User"];
[query whereKey:@"isTeacher" equalTo:@"False"];
[query setLimit: limit];
[query setSkip: skip];
[[[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (objects.count == limit) {
[self performTeacherQueryWithLimit:limit andSkip:skip+limit];
}
else{
NSArray *results = [NSArray arrayWithArray:objects];
NSLog(@"%@", results);
NSLog(@"%lu", (unsigned long)results.count);
NSLog(@"results^");
[self.searchResults addObjectsFromArray:results];
NSPredicate *searchPredicate =
[NSPredicate predicateWithFormat:@"SELF.name contains[c] %@",searchTerm];
_searchResults = [NSMutableArray arrayWithArray:[results filteredArrayUsingPredicate:searchPredicate]];
[self.searchDisplayController.searchResultsTableView reloadData];
NSLog(@"%@", _searchResults);
NSLog(@"%lu", (unsigned long)_searchResults.count);
NSLog(@"search results^");
}
}];
]]
}
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
[self filterResults:searchString];
return YES;
}
这段代码不起作用,因为我在底部调用filterResults而没有所有正确的参数,但这是因为我已经到了一半,现在我被卡住了。我知道我需要使用setSkip,但我不确定如何为我的搜索工作。任何帮助都是极好的!谢谢!
答案 0 :(得分:5)
我使用一种方法来处理查询及其结果,如下所示:
- (void)runQuery:(PFQuery *)query filling:(NSMutableArray *)array completion:(void (^)(BOOL))completion {
query.skip = array.count;
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error) {
[array addObjectsFromArray:objects];
if (objects.count < query.limit) {
return completion(YES);
} else {
[self runQuery:query filling:array completion:completion];
}
} else {
return completion(NO);
}
}];
}
像这样使用:
PFQuery *query = [PFQuery queryWithClassName:@"MyClass"];
// setup query
query.limit = // set this to a reasonable size
// the given method will do ceil(N / limit) finds, where N is the number
// of rows that satisfy the query
NSMutableArray *array = [@[] mutableCopy];
[self runQuery:query filling:array completion:^(BOOL success) {
NSLog(@"%@", array);
// you would do your local search and set search results here
}];
更具功能性的版本会在查询之间调用进度块。这将允许您不断更新结果。为此,只需添加进度块参数并在[array addObjectsFromArray:objects];
之后立即调用。