我想在单击按钮时将数据保存到核心数据中,这是我的操作按钮代码,现在是let app = UIApplication.sharedApplication().delegate as! AppDelegate let context = app.managedObjectContext let entity = NSEntityDescription.entityForName("Cart", inManagedObjectContext: context) let cart = Cart(entity: entity!, insertIntoManagedObjectContext: context)
,但是现在唯一的问题是我不怎么保存在这里,是我的代码来解析json
Alamofire.request(.GET, url!, headers: headers).responseJSON { (response) in
let result = response.result
if response.result.isSuccess{
let jsonObj = JSON(result.value!)
if let x = jsonObj["Items"].array {
x.forEach
{
if let uw = ($0["name"]).string{
print(uw)
let qw = ($0["image"]).string
if let rw = ($0["price"]).int{
if let hu = ($0["id"]).int{
print(hu)
let foo = Rest(name: uw, imageUrl: qw!, price: "₦\(rw)")
self.rest.append(foo)
}
}
}
}
dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData()
actInd.stopAnimating()
}
}
}
所以我有一个名为rest的数组,这是我想要获取tableview数据的地方。我想将每个单元格的信息保存到coredata中,这是应用程序的屏幕截图
因此,当点击确定按钮时,它将项目保存到coredata
这是我的代码,以防您nee code
最佳答案
试试看,以适应您的代码。
在您拥有的部分中(... let app = ...)替换为:
let app2 = UIApplication.sharedApplication().delegate as! UIApplicationDelegate
if let context2 = app2.managedObjectContext {
let cart2 = NSEntityDescription.insertNewObjectForEntityForName("Cart", inManagedObjectContext: context2) as! Cart
cart2.name = self.res.name
cart2.price = self.res.price
cart2.url = self.res.imageUrl
cart2.id = ""
// Perform a save operation
do {
try context2?.save()
} catch {
let saveError = error as NSError
print(saveError)
}
}
让我知道这个是否奏效。
干杯