我有作爲一個數組存儲在NSUserDefaults中的數據。我需要使用Parse Server將這些數據存儲在數據庫中。當我嘗試循環訪問數組並使用saveInBackgroundWithBlock時,循環在塊完成之前再次運行設置新值。將數據保存爲數據庫上的單個對象的最佳方法是什麼?如何在循環中快速保存背景
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")
}
})
}
查找到NSCondition類,它允許一個線程等待另一個線程完成。使用它你可以等待之前的save()完成,然後再次開始循環。 –
你想在Parse中包含多個'Other'對象嗎?還是包含兩個數組的對象? – Paulw11