在Parse中一次更新许多对象

时间:2015-07-13 05:10:40

标签: javascript ios swift parse-platform cloud-code

我需要一次更新一堆对象,由于文档建议调用.getObjectInBackgroundWithID,我无法一次找到有效的方法来完成所有操作。我没有对每个对象都有ID,即使我做了,我也无法全部通过它们。

问题: 1)在云代码中调用此函数比在客户端处理所有这些更有意义,对吧? 2)在JS(Cloud Code)/ Swift的for循环中更新具有相同值的多个对象的最佳方法是什么?

1 个答案:

答案 0 :(得分:2)

我认为您正在寻找.findObjects(及其变体)的查询,然后使用PFObject的类方法.saveAll(及其变体)来保存对象数组

这是sample

var query = PFQuery(className:"GameScore")
query.whereKey("playerName", equalTo:"Sean Plott")
query.findObjectsInBackgroundWithBlock {
  (objects: [AnyObject]?, error: NSError?) -> Void in

  if error == nil {
    // The find succeeded.
    println("Successfully retrieved \(objects!.count) scores.")
    // Do something with the found objects
    if let objects = objects as? [PFObject] {
      for object in objects {
        println(object.objectId)
        // Do your manipulation
      }

      // Save your changes to ALL objects
      PFObject.saveAllInBackground(objects, block: {
        (succeeded: Bool, error: NSError!) -> Void in

        if (error == nil) {
            println("Successfully saved \(objects!.count) objects.")
        } else {
            // Log details of the failure
            println("Error: \(error!) \(error!.userInfo!)")
      })
    }
  } else {
    // Log details of the failure
    println("Error: \(error!) \(error!.userInfo!)")
  }
}

CloudCode sample

var GameScore = Parse.Object.extend("GameScore");
var query = new Parse.Query(GameScore);
query.equalTo("playerName", "Dan Stemkoski");
query.find({
  success: function(results) {
    alert("Successfully retrieved " + results.length + " scores.");
    // Do something with the returned Parse.Object values
    for (var i = 0; i < results.length; i++) {
      var object = results[i];
      alert(object.id + ' - ' + object.get('playerName'));
    }
  },
  error: function(error) {
    alert("Error: " + error.code + " " + error.message);
  }
});