简体   繁体   中英

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)
        }
    })
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM