iOS - Análise - PFQuery não funciona
-
02-01-2020 - |
Pergunta
Estou criando uma classe personalizada ChatRequest
, mas quando tento consultá-lo, ele não retornará nenhuma chave personalizada.
Aqui está o meu código:
- (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];
}
}
Alguém pode ajudar?Verifiquei se minha aula estava correta e as chaves estavam lá, mas ainda não funciona.
Solução
Você não usa setValue
para adicionar uma restrição a uma consulta.Você usa whereKey:equalTo:
, então seu código deve ser:
- (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];
}
}
No entanto, por motivos de desempenho, é uma má ideia chamar os objetos find de forma síncrona desta forma.Você deveria usar - (void)findObjectsInBackgroundWithBlock:(PFArrayResultBlock)block
para permitir que a consulta seja concluída em segundo plano.No bloco de conclusão você pode atualizar sua IU.
Além disso, do ponto de vista do design, seu toUser
deve ser uma coluna de tipo de referência, não um tipo de string.Você poderia então usar
[query whereKey:@"toUser" equalTo:[PFUser currentUser]];