在 PFUser 注册后创建一个 PFObject 和 PFRelation

Create a PFObject and PFRelation after PFUser Sign Up

在我的结构中,我想注册一个用户并直接为其分配一个组(多对多关系模型)

以下是我注册用户的方式。完成后,我不知道如何使用 PFRelation 关联 PFObject。

有什么想法吗?

// SIGN UP USER
var user = PFUser();
user.email = emailTextField.text;
user.username = emailTextField.text;
user.password = passwordTextField.text;

user.signUpInBackgroundWithBlock({ (succeeded: Bool, error: NSError?) -> Void in
    if error == nil {
        //Create a PFObject
        var group = CustomPFObject();
        group.name = "My First Group";
    }
});

你可以这样做:

user.signUpInBackgroundWithBlock({ (succeeded: Bool, error: NSError?) -> Void in
    if error == nil {

        //Create a PFObject

        var group = CustomPFObject();
        group.name = "My First Group";

        var relation: PFRelation = group.relationForKey("your_key")

        relation.addObject(user)

        group.save() // synchronous

        group.saveInBackgroundWithBlock { (Bool, NSError?) -> Void in

        }   // async
    }
});

如何在 Parse.com

中建立关系
//first you create the user that will relate with something
var user = PFUser.currentUser()
//Then you create a relationship type eg. friend, likes, score (in this case like similar to facebook or twitter
var relation = user.relationForKey("likes")
//after you add the PFObject that it relates to eg. a friend, a post, a twitte (see how to acquire this PFObejct below)
relation.addObject(post)
//Now you just need to save the relation
user.saveInBackgroundWithBlock {
  (success: Bool, error: NSError?) -> Void in
  if (success) {
    // The post has been added to the user's likes relation.
  } else {
    // There was a problem, check error.description
  }
}

如果您需要获取一个 PFObject 以添加到关系中,您可以这样做:

var post = myComment["parent"] as PFObject
post.fetchIfNeededInBackgroundWithBlock {
  (post: PFObject?, error: NSError?) -> Void in
  let title = post?["title"] as? NSString
  // do something with your title variable
}

希望对你有帮助!