cb428
cb428

Reputation: 495

Access Parse Object ID right after instantiation

I'm creating two PFObjects at the same time that should reference each other's object IDs when they're saved. In the example below, the second object is supposed to save the first object's object ID in an array.

let objectForFirstClass = PFObject(className:"ClassOne")
let objectForSecondClass = PFObject(className: "ClassTwo")
objectForSecondClass.setObject([objectForFirstClass.objectId!], forKey: "classOneObjectArray")

The last line is causing the error because objectForFirstClass.objectId is nil. I'd assume this is because the object hasn't been saved yet. How can I fix this?

Upvotes: 0

Views: 27

Answers (2)

jcaron
jcaron

Reputation: 17710

You want to save after creating the first object, and in the completion handler, create the second one with a reference to the first one.

You can use saveAllInBackground:block: for this.

Upvotes: 0

Wain
Wain

Reputation: 119031

Correct, the object id is assigned by the server when saved. I'd be tempted to write some cloud code to do what you want so you can send some details and the cloud code will create and connect the objects, then return both of them to you. You can of course do the same thing locally in your app, there's just more network comms.

You should also consider using pointers or relationships. These are better for querying, though the same save requirements apply before you can set the connections.

Upvotes: 0

Related Questions