J.M J.M - 1 month ago 21
iOS Question

How to delete object from Parse via PFQuery

I am trying to delete an object from the class UserRequests via swift only if the object belongs to the current user, and that requestResponded is not equal to true. However, I get an error at

objects.deleteInBackground()
and the function still doesn't work when I remove this line.

func deleteRequest(){
let check = PFQuery(className: "UserRequests")
check.whereKey("requestResponded", equalTo: "True")

let query = PFQuery(className: "UserRequests")
query.whereKey("username", equalTo: (PFUser.currentUser()?.objectForKey("username") as! String))
query.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in
if objects != nil && error == nil{
// Successfully retrieved the object
check.getFirstObjectInBackgroundWithBlock {
(object: PFObject?, error: NSError?) -> Void in
if error != nil || object == nil {
print("Not accepted.")
object!.deleteInBackground()
objects.deleteInBackground()
} else {
print("Successfully retrieved the object.")
}
}
}else{
self.performSegueWithIdentifier("requestAccepted", sender: self)
}
})
}

Answer

It is because objects is an list of object. You should only delete object 1 by 1.

For example:

for object in objects {
    object.deleteInBackground()
}

Also, because two queries belong to same class. I would suggest using 1 query

UPDATE

func deleteRequest(){
    let query = PFQuery(className: "UserRequests")
    // the key "requestResponded" is not True
    query.whereKey("requestResponded", equalTo: "False")
    // for deleting the object is that it belongs to the current user
    query.whereKey("username", equalTo (PFUser.currentUser()?.objectForKey("username") as! String))
    query.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in
        if error != nil{
            print(error)
        }
        //  objects are those the key "requestResponded" is not True and belongs to the current user
        for object in objects {
            object.deleteInBackground()
        }
        // other case
        if objects.count == 0 { // no match result found
        }
    })
}

I guess you still miss the condition of when to perform segue