iOS - Parse - PFQuery Not Working
-
02-01-2020 - |
Question
I am creating a custom class ChatRequest
, but when I try to query it, it will not return any custom keys.
Here is my code:
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
PFQuery *query = [PFQuery queryWithClassName:@"ChatRequest"];
[query setValue:[PFUser currentUser].username forKey:@"toUser"];
NSArray *objects = [query findObjects];
for (NSUInteger i = 0; i < objects.count; i++) {
PFObject *object = [objects objectAtIndex:i];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Chat Request!" message:object.sendingUser + @"wants to chat with you!" delegate:self cancelButtonTitle:@"Decline" otherButtonTitles:@"Accept", nil];
[alertView show];
}
}
Can anyone help? I checked that my class was correct and the keys were there, but it still won't work.
Solution
You don't use setValue
to add a constraint to a query. You use whereKey:equalTo:
, so your code should be:
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
PFQuery *query = [PFQuery queryWithClassName:@"ChatRequest"];
[query whereKey:@"toUser" equalTo:[PFUser currentUser].username ];
NSArray *objects = [query findObjects];
for (NSUInteger i = 0; i < objects.count; i++) {
PFObject *object = [objects objectAtIndex:i];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Chat Request!" message:object.sendingUser + @"wants to chat with you!" delegate:self cancelButtonTitle:@"Decline" otherButtonTitles:@"Accept", nil];
[alertView show];
}
}
However, for performance reasons it is a bad idea to call the find objects synchronously like this. You should use - (void)findObjectsInBackgroundWithBlock:(PFArrayResultBlock)block
to allow the query to complete in the background. In the completion block you can refresh your UI.
Also, from a design point of view your toUser
should be a reference type column, not a string type. You could then use
[query whereKey:@"toUser" equalTo:[PFUser currentUser]];