问题:核心数据正在创建一个空条目,在发布到这里之前,我已经看到了所有可能的资源。
简短说明: 我有一个购物车,在其中检查产品是否已经存在,是否存在,我将计数更新为1。如果不存在,则将其添加到核心数据中并显示在集合视图中
当前情况,例如:
该值正在更新,但每次还会添加另一个空值。 假设我单击添加到购物车,然后将其添加到购物车,再次单击计数更新时,但同时添加了另一个空条目。因此,如果我按添加到购物车按钮5次,则主要对象的数量将变为5,但是还会添加另外4个空条目。
图片:
添加到核心数据的代码
@IBAction func addToCartAction(_ sender: Any){
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
let managedContext = appDelegate.persistentContainer.viewContext
let cartEntity = NSEntityDescription.entity(forEntityName: "Cart", in: managedContext)!
let imageViewModel = self.product?.images.items.first
let urlString: String = (imageViewModel?.url.absoluteString)!
let varientModel = self.product?.variants.items.first
let cart = NSManagedObject(entity: cartEntity, insertInto: managedContext)
if self.checkIfAlreadyInCart(handle: self.productHandle!)
{
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Cart")
request.predicate = NSPredicate.init(format: "productHandle = %@ AND variantName = %@", argumentArray: [self.productHandle!,self.selectedVariant!])
do {
let result = try managedContext.fetch(request) as? [Cart]
var currentValue = result![0].value(forKey: "productQty") as! Int
currentValue += 1
result![0].setValue(currentValue, forKey: "productQty")
try managedContext.save()
}
catch let error as NSError {
print("Could not save. \(error), \(error.userInfo)")
}
}
else{
cart.setValue(1, forKey: "productQty")
cart.setValue( self.product?.title, forKeyPath: "productName")
cart.setValue( self.product?.price, forKey: "productPrice")
cart.setValue( self.product?.price, forKey: "productComparePrice")
cart.setValue(urlString, forKey: "productImageUrl")
cart.setValue(self.productHandle, forKey: "productHandle")
cart.setValue(varientModel?.id, forKey: "productVariantID")
cart.setValue(varientModel?.title, forKey: "variantName")
do {
try managedContext.save()
}
catch let error as NSError {
print("Could not save. \(error), \(error.userInfo)")
}
}
}
,而self.checkIfAlreadyInCart(handle: self.productHandle!)
函数是:
func checkIfAlreadyInCart(handle: String) -> Bool{
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
do {
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Cart")
request.predicate = NSPredicate.init(format: "productHandle = %@ AND variantName = %@", argumentArray: [self.productHandle!,self.selectedVariant!])
let result = try context.fetch(request)
if result.count > 0 {
return true
}
else {
return false
}
}
catch {
print("Some exception occured.")
return false
}
}
欢迎任何建议或解决方案。如果您可以建议一些学习核心数据的好地方,那将是很好的,因为我对此知识的了解很少。