I am testing Parse local datastore to evaluate if I can use it as a replacement for SQLite for an app that would mostly be used offline. I may have found a bug?
Consider the Product and Order classes:
class Product : PFObject, PFSubclassing {
@NSManaged var productName: String!
}
class Order : PFObject, PFSubclassing {
@NSManaged var orderId: String!
@NSManaged var product: Product!
}
With internet disabled, when I run the following code, it crashes on the last line with Tried to save an object with a new, unsaved child.
let p = Product()
p.productName = "Test Product"
p.saveEventually()
let o = Order()
o.orderId = "TestOrder01"
o.product = p
o.saveEventually()
let query = Order.query()
query.whereKey("product", equalTo: p)
let results = query.findObjects() // crashes with Tried to save an object with a new, unsaved child.
is it a platform limitation or a bug in my code?
NOTE I have typed the code from memory, so ignore minor issues.
This is caused by your use of
saveEventually
causing a racing condition, like so:You need to ensure the parent is saved before creating a child.
Instead, do a saveInBackGroundWithBlock on the Product, then do the creation and save of the Order in the completion block.