Riley Osborne
Riley Osborne

Reputation: 35

Swift Parse Query Using A Pointer

I have to query for a class called "Commitment" it has a pointer called "need". I need to be able to access the data in the pointer of need while querying Commitment. I have to query for Commitment because I have to check the "committer" object against the current user. Essentially I want to be able to see the needs that the current user has committed to.

Commitment Class:

ScreenShot

Need Class:

ScreenShot

let query = PFQuery(className: "Commitment")
     query.order(byDescending: "createdAt")
    query.whereKey("committer", equalTo:  PFUser.current()!)
    query.includeKey("need")
    query.findObjectsInBackground {
        (objects: [PFObject]?, error: Error?) -> Void in
        if let objects = objects as [PFObject]? {
            self.committment = []
            self.commitObject = []
            for object in objects {

                self.committment.append(Committment(id: object.objectId!, needName: object["needName"] as! String))
                self.commitObject.append(object)
            }
            self.tableView.reloadData()
        } else {
            print("failure")
        }
    }

This is my current query. It returns nil on needName so obviously that isn't working. Any help is appreciated.

Upvotes: 0

Views: 770

Answers (1)

Ran Hassid
Ran Hassid

Reputation: 2788

The reason that you get nil is because you are not accessing the need object but you are trying to get it from the Commitment object just change your code to something like this:

let query = PFQuery(className: "Commitment")
     query.order(byDescending: "createdAt")
    query.whereKey("committer", equalTo:  PFUser.current()!)
    query.includeKey("need")
    query.findObjectsInBackground {
        (objects: [PFObject]?, error: Error?) -> Void in
        if let objects = objects as [PFObject]? {
            self.committment = []
            self.commitObject = []
            for object in objects {
                let need = object["need"] as [PFObject]?
                self.committment.append(Committment(id: object.objectId!, needName: need["needName"] as! String))
                self.commitObject.append(object)
            }
            self.tableView.reloadData()
        } else {
            print("failure")
        }
    }

Notice that i first access the need object and from there extract the needName property.

BTW! i am not sure that the syntax is 100% accurate (i wrote it in freestyle) but i am sure that you got the idea..

Upvotes: 3

Related Questions