1

So, I have a query in parse that has to find objects based on whether a key is equal to a certain object. Here is the few lines of code.

    var gamesQuery = PFQuery(className: "Games")
    gamesQuery.whereKey("challenged", equalTo: (PFUser.currentUser()!.objectId!))
    gamesQuery.whereKey("challenger", equalTo: PFUser.currentUser()!)

However, when this query is ran, the query is occasionally found as nil due to the fact that there is no object that fits the search parameters.

Is there any check that I could run that could check if

gamesQuery.whereKey("challenged", equalTo: (PFUser.currentUser()!.objectId!))

is nil? Any help with this issue would be very appreciated.

Aidan Kaiser
  • 501
  • 5
  • 17
  • I don't understand your question - Do you want to check to see that there are no records with challenged==current user independent of challenger==current user? You seem to be looking for games where the user has challenged themselves? – Paulw11 Oct 27 '15 at 01:09
  • No, thats not what I am doing, sorry if this code is a bit out of context. In this game, a user can either challenge someone or be challenged. So, I am searching for any games in which a single user has been challenged or challenged someone else. I am looking for a way to test if either challenged==current user or challenger==current user is nil. @Paulw11 – Aidan Kaiser Oct 27 '15 at 01:57
  • You can disregard the code, its more of just an example. All I am looking for is a way to check if a "whereKey is equal to" statement is nil. @Paulw11 – Aidan Kaiser Oct 27 '15 at 02:00
  • Do you mean where a query returns no objects? – Paulw11 Oct 27 '15 at 02:09
  • No, I get an error when there is no object that fits the parameters of challenged==currentUser and challenger==currentUser. I need something to check if these two statements are nil. @Paulw11 – Aidan Kaiser Oct 27 '15 at 02:49

1 Answers1

2

Your current query is essentially an and - "find objects where challenged==current user and challenger==current user".

I think you are after an or query - "find objects where challenged==current user or challenger==current user". You can do this with a compound query in Parse -

let challengedQuery = PFQuery(className: "Games")
challengedQuery.whereKey("challenged", equalTo: (PFUser.currentUser()!.objectId!))

let challengerQuery = PFQuery(className: "Games")
challengerQuery.whereKey("challenger", equalTo: PFUser.currentUser()!)

let gamesQuery = PFQuery.orQueryWithSubqueries([challengedQuery, challengerQuery])

gamesQuery.findObjectsInBackgroundWithBlock {
  (results: [PFObject]?, error: NSError?) -> Void in
  if error == nil {
     // results contains challenger and challenged games.
  }
}
Paulw11
  • 108,386
  • 14
  • 159
  • 186