如何从UITextField中检索字符串,将其用于PFQuery的解析查询,然后加载到表视图



我想创建一个没有搜索栏显示的基本搜索功能。我为输入文本创建了一个UITextfield,为PFQuery创建了一个搜索按钮,并在其中显示搜索结果的表视图。(用户在文本框中输入一个名称,按回车键,如果有匹配的结果将出现在表视图中。)

我尝试使用此代码进行查询,但没有成功。xcode显示"未使用的变量'user'",与searchResult相同。我不明白为什么这些变量没有被使用。

来自日志:

一个长时间运行的Parse操作正在主线程上执行。在warnParseOperationOnMainThread()上中断调试

my .m file:

@interface TestViewController () 
@end
@implementation TestViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// mainArray = [query findObjects];
mainArray = [[NSArray alloc] initWithObjects:@"user", nil];
}
-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [mainArray count];
}
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"thisCell"];
cell.textLabel.text = [mainArray objectAtIndex:indexPath.row];
return cell;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

- (IBAction)searchButton:(id)sender {
  NSString *searchResult = [self.searchField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
PFQuery *query = [PFUser query];
[query whereKey:@"username" equalTo:@"searchResult"];
PFUser *user = (PFUser *)[query getFirstObject];
// NSArray *searchedItem = [query findObjects];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self.view endEditing:YES];
}
@end

. h文件:

@interface TestViewController :UIViewController<UITableViewDelegate,UITableViewDataSource>{
    IBOutlet UITableView *tableView;
    NSArray *mainArray;
    NSString *searchResult;
}
@property (weak, nonatomic) IBOutlet UITextField *searchField;
- (IBAction)searchButton:(id)sender;
@end

没有错误。"Unused"是一个警告,表示您没有将"user"变量用于任何用途。当然,你给了它一个值,但你之后没有使用那个值。一个简单的调用NSLog来显示一些东西就会删除这个警告:

NSLog(@"Username: %@", user[@"username"];

而且,正如shim所说,关于长时间运行的Parse操作的警告是因为您使用了

[query getFirstObject];

在主线程上运行。要去掉这个警告,可以使用一个背景函数,比如

[query getFirstObjectInBackgroundWithBlock:^(PFObject *object, NSError *error) {
  if (object) {
    PFUser *user = (PFUser *)object;
    NSLog(@"Username: %@", user[@"username"]);
  }
}];

像这样编辑函数(searchResult不加引号):

- (IBAction)searchButton:(id)sender {
  NSString *searchResult = [self.searchField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
  PFQuery *query = [PFUser query];
  [query whereKey:@"username" equalTo:searchResult];
  PFUser *user = (PFUser *)[query getFirstObject];
  // NSArray *searchedItem = [query findObjects];
}

最新更新