0

I have a class named Pet. I collect it in an array. Then I try to save it like below code. I also tried inheriting NSObject to the Pet class with no use. Is it not possible to save my own class of arrays in Parse or am I doing something really wrong? Note that the current user exists and valid.

Somewhere in code defined:

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

populated:

pets.append(newPet)

and tried to save:

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

The error I am getting is:

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. I am a beginner in Swift as well as Parse. Any help is appreciated.

oyalhi
  • 3,834
  • 4
  • 40
  • 45

1 Answers1

1

Parse is likely trying to serialize the "pets" array into JSON. However, your "Pet" class is not serializable to JSON.

From the 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.

You need to create a method on your Pet class that converts it to a Dictionary, as described in this Stack Overflow answer.

Community
  • 1
  • 1
  • Hmm. I need to dig in a little deeper. The example is Obj-C, I wish it were in swift. Thanks though, my search was empty, now I have something to work with. – oyalhi Feb 18 '15 at 07:38