gpt4 book ai didi

ios - 将数据列表保存到核心数据 iOS Swift

转载 作者:行者123 更新时间:2023-11-29 01:20:28 28 4
gpt4 key购买 nike

我在这里使用 for each 循环将数据列表保存到核心数据中。但是,它只是帮助我将for循环中的最后一个数据保存到核心数据中,这是什么问题?我无法将所有数据保存到核心数据中。下面是我正在处理的代码...

let appDelegate : AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context : NSManagedObjectContext = appDelegate.managedObjectContext
let category = NSEntityDescription.insertNewObjectForEntityForName("Category", inManagedObjectContext:context)


RestApiManager.sharedInstance.makeGetRequest("testingserver", onCompletion: {json in
for result in json["record"].arrayValue
{
print(result)
let id = result["mc_termid"].stringValue
let name = result["mc_name"].stringValue
let parent = result["mc_parent"].stringValue
let color = result["mc_color"].stringValue
let update = result["mc_updated"].stringValue
let termName = result["mc_termname"].stringValue
let status = result["mc_status"].stringValue

category.setValue(id, forKey: "mc_termid")
category.setValue(name, forKey: "mc_name")
category.setValue(parent, forKey: "mc_parent")
category.setValue(color, forKey: "mc_color")
category.setValue(update, forKey: "mc_updated")
category.setValue(termName, forKey: "mc_termname")
category.setValue(status, forKey: "mc_status")
}
do
{
try context.save()
print("Category save to local database successfully.")
}
catch
{

}
})

最佳答案

每次迭代数组中的一个元素时,都需要插入一个托管对象。
所以将类别声明放入迭代 block 中。

let appDelegate : AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context : NSManagedObjectContext = appDelegate.managedObjectContext


RestApiManager.sharedInstance.makeGetRequest("testingserver", onCompletion: {json in
for result in json["record"].arrayValue
{
let category = NSEntityDescription.insertNewObjectForEntityForName("Category", inManagedObjectContext:context)

print(result)
let id = result["mc_termid"].stringValue
let name = result["mc_name"].stringValue
let parent = result["mc_parent"].stringValue
let color = result["mc_color"].stringValue
let update = result["mc_updated"].stringValue
let termName = result["mc_termname"].stringValue
let status = result["mc_status"].stringValue

category.setValue(id, forKey: "mc_termid")
category.setValue(name, forKey: "mc_name")
category.setValue(parent, forKey: "mc_parent")
category.setValue(color, forKey: "mc_color")
category.setValue(update, forKey: "mc_updated")
category.setValue(termName, forKey: "mc_termname")
category.setValue(status, forKey: "mc_status")
}
do
{
try context.save()
print("Category save to local database successfully.")
}
catch
{

}
})

关于ios - 将数据列表保存到核心数据 iOS Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34668347/

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