gpt4 book ai didi

ios - 如何快速循环保存在后台

转载 作者:行者123 更新时间:2023-11-30 13:36:33 24 4
gpt4 key购买 nike

我将数据作为数组存储在 NSUserDefaults 中。我需要使用 Parse Server 获取这些数据并将其存储在数据库中。当我尝试循环遍历数组并使用 saveInBackgroundWithBlock 时,循环会在 block 完成之前再次运行并设置新值。将此数据保存为数据库中的单独对象的最佳方法是什么?

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

最佳答案

您需要在 for 循环内分配 PFObject ,否则您只是一遍又一遍地弄乱同一个对象。

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 {
let other = PFObject(className: "Other")
other.setObject(PFUser.currentUser()!, 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")
}
})
}

作为

关于ios - 如何快速循环保存在后台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36002726/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com