在PFQueryTableView中搜索不起作用

时间:2015-03-28 03:29:46

标签: ios objective-c parse-platform uisearchbar pfquery

我有使用UISearchBar的PFQueryTableView来搜索Parse服务器上的用户类中的用户,但我从来没有让它工作。这是我的代码:

SearchViewController.h

#import <Parse/Parse.h>
@interface PAWUserSearch1ViewController : PFQueryTableViewController
@end

SearchViewController.m

#import "SearchViewController.h"
#import "PAWAppDelegate.h"

@interface SearchViewController () <UIGestureRecognizerDelegate, UISearchBarDelegate, UISearchDisplayDelegate>
@property (strong, nonatomic) IBOutlet UISearchBar *searchBar;
@property (nonatomic, strong) UISearchDisplayController *searchController;
@end

@implementation SearchViewController

- (id)initWithStyle:(UITableViewStyle)style {
    self = [super initWithStyle:style];
    if (self) {
        self.parseClassName = [PFUser parseClassName];
        self.pullToRefreshEnabled = NO;
        self.paginationEnabled = YES;
        self.objectsPerPage = self.objects.count;
    }
    return self;
}

- (PFQuery *)queryForTable {
    NSLog(@"searchbar text --> %@", self.searchBar.text);

    PFQuery *query = [PFUser query];
    if ([self.searchBar.text length]!=0) {
        PFQuery *userQuery = [PFUser query];
        [userQuery whereKey:kPAWParseUsernameKey matchesRegex:self.searchBar.text modifiers:@"i"];
        [query whereKey:kPAWParseUserKey matchesKey:@"objectId" inQuery:userQuery];
    } else {
        [query whereKeyExists:@"featuredNote"]; //show only users with location detailed
    }

    return query;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSLog(@"number of users --> %i", self.objects.count);
    return self.objects.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *identifier = @"reuseIdentifier";
    UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:identifier];

    if (!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                  reuseIdentifier:identifier];
    }

    // display user name
    NSString *userNameWithLocation = [NSString stringWithFormat:@"@%@ -%@", [self.objects[indexPath.row] objectForKey:kPAWParseUsernameKey], [self.objects[indexPath.row] objectForKey:@"featuredNote"]];
    cell.textLabel.text = userNameWithLocation;
    cell.textLabel.textColor = [UIColor darkGrayColor];

    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 70.0;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    //set nav
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Done", nil) style:UIBarButtonItemStylePlain target:self action:@selector(doneButtonPressed:)];

    self.pullToRefreshEnabled = NO;

    // Hide the search bar until user scrolls up
    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];
    self.tableView.tableHeaderView = self.searchBar;
    self.searchBar.delegate = self;

    self.searchController = [[UISearchDisplayController alloc] initWithSearchBar:self.searchBar
                                                          contentsController:self];
    self.searchController.searchResultsDataSource = self;
    self.searchController.searchResultsDelegate = self;
    self.searchController.delegate = self;

    CGPoint offset = CGPointMake(0, self.searchBar.frame.size.height);
    self.tableView.contentOffset = offset;

    self.searchBar.placeholder = NSLocalizedString(@"Username", nil);
}

- (IBAction)doneButtonPressed:(id)sender {
    [self.presentingViewController dismissModalViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    NSLog(@"search pressed!!!!!!");
    [searchBar resignFirstResponder];
    //[self.tableView reloadData];
    [self loadObjects];
}
@end

此代码显示所有用户,如果他们的“featuredNote”退出 - 这部分工作正常,但当我搜索它不显示搜索结果。我在搜索框中键入了一个关键字,当我点击键盘上的搜索时,会触发 searchBarSearchButtonClicked 方法,但就是这样。我希望能够调用 queryForTable ,但事实并非如此。因此,该表仍然将所有用户显示为原始用户。我做错了什么或者我错过了什么?请帮忙。非常感谢你。

更新

由于我已经用 [self loadObjects]; 替换了 [self.tableView reloadData]; ,我可以调用 queryForTable searchBarSearchButtonClicked 之后。但是, tableView numberOfRowsInSection 仍然总是返回零。

2 个答案:

答案 0 :(得分:1)

您正在设置查询,但您没有告诉它进行搜索,您需要执行以下操作:

[query whereKeyExists:@"featuredNote"];//this sets the query

[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {

    //Your code here


}];//this PERFORMS the query

答案 1 :(得分:0)

这是来自具有类似实现需求的项目的代码you asked for。我最终使用UISearchBar和单独的UITableView来显示结果。确保在实施时为UISearchBarUITableView建立正确的Storyboard连接。此外,搜索栏的delegate应设置为ViewController,并且表格视图的delegatedataSource应设置为ViewController

static NSString * const kSearchResultsTableCellReuseIdentifier = @"SearchResultsTableCellReuseIdentifier";

@interface ViewController ()
    @property (nonatomic, strong) NSArray *searchResults;
    @property (nonatomic, weak) IBOutlet UISearchBar *searchBar;
    @property (nonatomic, weak) IBOutlet UITableView *searchResultsTable;
@end

@implementation ViewController

...

#pragma mark - Protocol conformance

#pragma mark UISearchBarDelegate methods

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    if([searchText length] == 0)
    {
        [self dismissSearch];
    }
    else
    {
        [self handleSearchForString:searchText];
    }
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    // any logic related to Search button being clicked
}

#pragma mark UITableViewDataSource methods

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.searchResults count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [self.searchResultsTable dequeueReusableCellWithIdentifier:kSearchResultsTableCellReuseIdentifier];

    if (!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kSearchResultsTableCellReuseIdentifier];
    }

    // Search result text to be displayed in table
    cell.textLabel.text = [self.searchResults objectAtIndex:indexPath.row].name;

    return cell;
}

#pragma mark UITableViewDelegate methods

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // any logic for when a cell in the search results table is selected

    [self dismissSearch];
}    

#pragma mark - Helpers

- (void)handleSearchForString:(NSString *)searchString
{
    // any logic for retrieving search results as an NSArray we'll call `results`

    self.searchResults = results;
    [self.searchResultsTable reloadData];

}

- (void)dismissSearch
{
    self.searchBar.text = @"";

    [self.searchBar performSelector: @selector(resignFirstResponder)
                      withObject: nil
                      afterDelay: 0.1];
}

@end

希望有所帮助