我已经使用核心数据成功添加并获取了一些数据。我的实体属性具有以下方案:productName,价格和数量。
价格和数量在控制台中正确显示。另一方面,产品名称是用阿拉伯语写的,因此用诸如“ \ U062c \ U064a \ U0628 \ U0627 \ U0644 \ U062a \ U0627 \ U062c \ U0631”之类的奇怪字符显示;
保存到核心数据代码:
@IBAction func submitOrderButton(_ sender: UIButton) {
let newItem = NSEntityDescription.insertNewObject(forEntityName: "OrderDetail", into: context)
newItem.setValue(String(self.productName.text!), forKey: "productName")
newItem.setValue(Int(self.productPrice.text!), forKey: "price")
newItem.setValue(self.orderQuantity, forKey: "quantity")
do{
try context.save()
}
catch{
// display in a uialert message
print("error has occured")
}
print("\(orderQuantity) items of this product")
}
从核心数据代码中获取
func fetchOrderDetails(){
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let fetchedOrders = NSFetchRequest<NSFetchRequestResult>(entityName: "OrderDetail")
fetchedOrders.returnsObjectsAsFaults = false
do{
let result = try context.fetch(fetchedOrders)
if result.count > 0{
print()
}
}
catch{
}
}
控制台中的输出:
<OrderDetail: 0x604000480af0> (entity: OrderDetail; id: 0xd000000000040000 <x-coredata://109134CB-DCF5-45D8-9298-E8B43C51E5DA/OrderDetail/p1> ; data: {
price = 3;
productName = "\U062c\U064a\U0628 \U0627\U0644\U062a\U0627\U062c\U0631";
quantity = 2;
})
谢谢!
更新
我要做的就是访问属性,然后可以将其分配给标签或在控制台中打印。两者都起作用。 下面是我添加的代码:
do{
let result = try context.fetch(fetchedOrders)
if result.count > 0{
// added code
var tempProd = result[0] as! NSManagedObject
productName.text = "\(tempProd.value(forKey: "productName"))"
for data in result as! [NSManagedObject]{
print(data.value(forKey: "productName") as! String)
}
// end of added code
}
}