I have data stored in NSUserDefaults as an array. I need to take this data and store it on a database using Parse Server. When I try to loop through the array and use saveInBackgroundWithBlock the loop runs again setting new values before the block completes. What is the best way to save this data as individual objects on the database?
let other = PFObject(className: "Other")
if (NSUserDefaults.standardUserDefaults().objectForKey("otherTypes") != nil) && (NSUserDefaults.standardUserDefaults().objectForKey("otherCosts") != nil) {
otherCosts = NSUserDefaults.standardUserDefaults().objectForKey("otherCosts") as! [Double]
otherTypes = NSUserDefaults.standardUserDefaults().objectForKey("otherTypes") as! [String]
for costs in otherCosts {
other.setObject(PFUser.currentUser()!.objectId!, forKey: "userId")
other.setObject(otherTypes[i], forKey: "otherName")
let cost = String(costs)
other.setObject(cost, forKey: "otherCost")
i = i + 1
other.saveInBackgroundWithBlock({ (success, error) -> Void in
if error == nil {
print("Success")
NSUserDefaults.standardUserDefaults().setObject(nil, forKey: "otherTypes")
NSUserDefaults.standardUserDefaults().setObject(nil, forKey: "otherCosts")
} else {
print("Fail")
}
})
}