我有一个UITableViewController
,其中有UISearchBar
搜索Parse.com用户。当我搜索类型“abc”时,我希望所有使用字符串“abc”的用户不仅仅是壁橱匹配。
·H
@property (weak, nonatomic) IBOutlet UISearchBar *searchBar;
@property (nonatomic, strong) PFUser *foundUser;
@property (nonatomic, strong) PFRelation *friendsRelation;
@property (nonatomic, strong) NSArray *allUsers;
@property (nonatomic, strong) PFUser *currentUser;
的.m
- (void)viewDidLoad {
[super viewDidLoad];
self.searchBar.delegate = self;
}
-(void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
PFQuery *query = [PFUser query];
[query orderByAscending:@"username"];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error){
if (error) {
NSLog(@"Error: %@ %@", error, [error userInfo]);
} else {
self.allUsers = objects;
[self.tableView reloadData];
}
}];
self.currentUser = [PFUser currentUser];
}
#pragma mark -search bar
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
//dismiss keyboard and reload table
[self.searchBar resignFirstResponder];
[self.tableView reloadData];
}
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
//Enable the cancel button when the user touches the search field
self.searchBar.showsCancelButton = TRUE;
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {
//disable the cancel button when the user ends editing
self.searchBar.showsCancelButton = FALSE;
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
//dismiss keyboard
[self.searchBar resignFirstResponder];
//reset the foundUser property
self.foundUser = nil;
//Strip the whitespace off the end of the search text
NSString *searchText = [self.searchBar.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
searchText = [searchText lowercaseString];
//Check to make sure the field isnt empty and Query parse for username in the text field
if (![searchText isEqualToString:@""]) {
PFQuery *query = [PFUser query];
[query whereKey:@"username" containsString:searchText];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error) {
//check to make sure the query actually found a user
if (objects.count > 0) {
//set your foundUser property to the user that was found by the query (we use last object since its an array)
self.foundUser = objects.lastObject;
//The query was succesful but returned no results. A user was not found, display error message
} else {
}
//reload the tableView after the user searches
[self.tableView reloadData];
} else {
//error occurred with query
}
}];
}
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
if (self.foundUser) {
return 1;
} else {
return 0;
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
if (self.foundUser) {
return 1;
} else {
return 0;
}
}
如何搜索字符串并检索具有该字符串的所有用户?