How to convert PFObject to PFRelation

195 Views Asked by At

Here is my code in Swift

@IBAction func addUser(sender: AnyObject) {
    var query = PFUser.query()
    query.whereKey("username", equalTo: usernameTextField)
    query.getFirstObjectInBackgroundWithBlock{ (objects:PFObject!, error: NSError!) -> Void in

        if error == nil {
            var friendList = PFUser.currentUser().relationForKey("friends") // I  don't understand relationforKey, what does it do? and what happen inside ( )?

            var addFriend = objects
            if addFriend != nil {
                PFRelation.addObject(addFriend!) // <- error here
                println("added")
            }
            PFUser.currentUser().saveInBackgroundWithBlock{
                (succeeded: Bool!, error: NSError!) in

                if error != nil {
                    println("Error")
                }
                else {
                    println("saved")
                }
            }
        }

    }
}

I want to let my app be able to add other users via their username with Parse and I have trouble with PFRelation.addObject(addFriend!). It shows that I cannot add PFObject into this method since inside ( ) has to be PFRelation object but I don't know how to convert this.
Any helps is appreciated. Thank you!

1

There are 1 best solutions below

0
On BEST ANSWER

First of all, make sure that you have the correct naming convention. Does usernameTextField is an instance of UITextField or String? Be careful for it.

For your question, your PFRelation does not know which objects to associate. How can it relate using addObject then? Also, you can not directly call addObject using PFRelation because addObject is not a factory method.

Here is something that you need to do, I just type it here and it might have errors:

let currentUser = PFUser().currentUser()
let relation = currentUser.relationForKey("friend") // assume that name of your relation column is friend
relation.addObject(objects) // please be careful for your naming convention. You should use object as a name here

// Then save using saveInBackgroundWithBlock