将我自己的 class 保存为 Parse 中的数组

Save my own class as an array in Parse

我有一只名为 class 的宠物。我把它收集在一个数组中。然后我尝试像下面的代码一样保存它。我还尝试将 NSObject 继承给 Pet class 但没有用。无法在 Parse 中保存我自己的 class 数组,还是我做错了什么?请注意,当前用户存在且有效。

代码中某处定义:

var pets : [Pet] = [Pet]()

人口:

pets.append(newPet)

并尝试保存:

@IBAction func saveTapped(sender: UIBarButtonItem) {
    PFUser.currentUser().setObject(pets, forKey: "pets")

    user.saveInBackgroundWithBlock({ (success, error) -> Void in
        if error == nil {
            DLog("Suceess saving")
        } else {
            displayAlertWithTitle(self, nil, error.description)
            DLog(error)
        }
    })
}

我得到的错误是:

2015-02-17 18:28:59.906 Patikoy[38292:2121589] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (Patikoy.Pet)'

p.s。我是 Swift 和 Parse 的初学者。感谢任何帮助。

Parse 可能会尝试将 "pets" 数组序列化为 JSON。但是,您的 "Pet" class 无法序列化为 JSON.

来自NSJSONSerialization Class Reference

An object that may be converted to JSON must have the following properties:

  • The top level object is an NSArray or NSDictionary.

  • All objects are instances of NSString, NSNumber, NSArray, NSDictionary, or NSNull.

  • All dictionary keys are instances of NSString.

  • Numbers are not NaN or infinity.

您需要在宠物 class 上创建一个方法,将其转换为字典,如 this Stack Overflow answer 中所述。