从Core Data Swift删除值时,错误域= NSCocoaErrorDomain代码= 1570

时间:2019-06-27 12:46:48

标签: ios swift firebase-realtime-database core-data

我知道了

  

Error Domain = NSCocoaErrorDomain代码= 1570“该操作无法   完成。 (可可错误1570。)”

两个曾经起作用的功能出错。

第一个deleteOrder()是Firebase观察者调用的函数。为了解决离线设备问题,我更改了删除条目的逻辑,从简单地删除条目改为在专用的"Deleted Orders"节点中使它们扭曲,在将观察者从.childRemoved的{​​{1}}更改之后我在"Orders"节点上的childAdded节点上声明出现此错误。 "Deleted Orders"尚未更改,但是现在deleteOrder()在保存时引发错误。据我所知,发现CoreData是保存到(Cocoa error 1570.)时遇到的一些丢失的非可选参数,就像我以前使用CoreData函数所经历的那样,但是从saveOrder()删除时我无法解释。

从接收订单或取消订单时保持库存更新的两个功能之一中,我也得到了相同的错误。 CoreData在收到新订单时工作完美,但是decrementInventory()在收到订单取消时抛出incrementInventory()。您能帮我找出错误在哪里吗?我一直在研究(Cocoa error 1570.)decrementInventory()之间的代码差异,但它们只是在相反的方向上做确切的事情。

一如既往,无限感谢您的时间和帮助。

功能是:

Firebase观察器:

incrementInventory()

deleteOrder():

static func getDeletedOrders(completed: @escaping (Bool) -> ()) {
        print("getDeletedOrders() : started")
        let ref = Database.database().reference()
        // Deleted Orders
        // Using .childAdded on new Deleted Orders node
        ref.child("Continent").child("Europe").child("Country").child(UserDetails.country!).child("Region").child(UserDetails.region!).child("City").child(UserDetails.city!).child("Shops").child(UserDetails.fullName!).child("Deleted Orders").observe(.childAdded, with: { (snapshot) in
            print("snapshot is: \(snapshot)")
            guard let value = snapshot.value as? [String : String] else {return}
            let orderId = value["Order Id"]!
            let customerName = value["User Name"]!
            let customerFcmToken = value["User fcmToken"]!
            let itemsIdList = value["Items Id List"]!
            do {
                try Order.deleteOrder(completed: { (true) in
                    if #available(iOS 10.0, *) {
                        // Local Notification
                        let actions: [UNNotificationAction] = [UNNotificationAction(identifier: "chiudi", title: "Chiudi", options: [.foreground])]
                        LocalNotifications.newTimeIntervalNotification(notificationType: "Deleted order", actions: actions, categoyIdentifier: "Deleted order", title: "Ordine", body: "Un ordine è stato cancellato", userInfo: [:], timeInterval: 0.1, repeats: false)
                    } else  if #available(iOS 9.0, *){
                        // Local Notification
                        LocalNotifications.newTimeIntervalNotification(notificationType: "Deleted order", actions: [], categoyIdentifier: "Deleted order", title: "Ordine", body: "Un ordine è stato cancellato", userInfo: [:], timeInterval: 0.1, repeats: false)
                    }
//                    // send push to customer
//                    PushNotifications.sendPushNotification(to: customerFcmToken, title: "Order number: \(String(describing: orderId))", subtitle: " Shop: \(String(describing: UserDetails.fullName!))", body: "Thank you \(customerName) we received your order cancellation. We'll be happy to see you next time you shop with us again. Bye.")

                    // localized push

                    PushNotifications.sendPushNotification(to: customerFcmToken, title: String(format: NSLocalizedString( "ORDER_DELETED_PUSH_TITLE", comment: ""), orderId), subtitle: String(format: NSLocalizedString( "ORDER_DELETED_PUSH_SUBTITLE", comment: ""), UserDetails.fullName!), body: String(format: NSLocalizedString("ORDER_DELETED_PUSH_BODY", comment: "") , customerName))

                } ,orderId: orderId, itemsIdList: itemsIdList)
                print("getDeletedOrders() : ended, now observing")
                completed(true)
            } catch {
                print("getDeletedOrders() : Error in saving snapshot to Core Data : \(error)")
            }
        })
    }

incrementInventory():

static func deleteOrder(completed: @escaping(Bool) -> (), orderId: String, itemsIdList: String) throws {
        let context = CoreData.databaseContext
        let request: NSFetchRequest<Order> = Order.fetchRequest()
        request.sortDescriptors = [NSSortDescriptor( key: "orderId", ascending: true)]
        request.predicate = NSPredicate(format: "orderId == %@", orderId)
        do {
            let fetch = try context.fetch(request)

            if fetch.count > 0 {
                for value in fetch {
                    do {
                        print("Order.deleteOrder() : fetch.count is: \(fetch.count)")
                        print("Order.deleteOrder() : found order is: \(value)")
                        context.delete(value)

                        print("Order.deleteOrder() : Order deleted")
                        var productIdListArray:[String] = value.itemsIdList!.components(separatedBy: ",")
                        for product in 0..<productIdListArray.count {
                            do {

                                try Product.incrementIventory(completed: { (true) in
                                    print("Order.deleteOrder() : Inventory seccessfully updated after order cancellation")


                                }, productId: productIdListArray[product])
                            } catch {
                                print("Error in incrementing inventory : \(error)")
                            }
                        }
                    }
                    do {
                        try context.save()
                        print("Order.deleteOrder() : Order deletion is saved")
                        completed(true)
                    } catch  {
                        print("Order.deleteOrder() : Error saving Order deletion: \(error)")
                    }
                }
            }
        } catch  {
            print("Order.deleteOrder() : Erron: Order not found")
        }
    }

和正常工作的 decrementInventory():

static func incrementIventory(completed: @escaping (Bool) -> (), productId: String) throws {
        print("Product.incrementIventory() : started")
        let context = CoreData.databaseContext
        let request: NSFetchRequest<Product> = Product.fetchRequest()
        request.predicate = NSPredicate(format: "productId == %@", productId)
        do {
            let fetch = try context.fetch(request)
            print("Product.incrementIventory(): fetching product")
            if fetch.count > 0 {
                for value in fetch {
                    //                if value.productId == productId {
                    if #available(iOS 10.0, *) {
                        let newAvailableQuantity = Int(value.availableQuantity!)! + 1
                        let newSoldQuantity = Int(value.soldQuantity!)! - 1
                        value.setValue(String(describing: newAvailableQuantity) , forKey: "availableQuantity")
                        value.setValue(String(describing: newSoldQuantity), forKey: "soldQuantity")

                        let ref = Database.database().reference()
                        ref.child("Continent").child("Europe").child("Country").child("\(UserDetails.country!)").child("Region").child(UserDetails.region!).child("City").child(UserDetails.city!).child("Catalog").child("\(productId)").child("Available Quantity").setValue(String(describing: newAvailableQuantity))
                        ref.child("Continent").child("Europe").child("Country").child("\(UserDetails.country!)").child("Region").child(UserDetails.region!).child("City").child(UserDetails.city!).child("Catalog").child("\(productId)").child("Sold Quantity").setValue(String(describing: newSoldQuantity))
                    } else {
                        // Fallback on earlier versions
                        let newAvailableQuantity = Int(value.availableQuantity!)! + 1
                        let newSoldQuantity = Int(value.soldQuantity!)! - 1
                        value.setValue(String(describing: newAvailableQuantity) , forKey: "availableQuantity")
                        value.setValue(String(describing: newSoldQuantity), forKey: "soldQuantity")

                        let ref = Database.database().reference()
                        ref.child("Continent").child("Europe").child("Country").child("\(UserDetails.country!)").child("Region").child(UserDetails.region!).child("City").child(UserDetails.city!).child("Catalog").child("\(productId)").child("Available Quantity").setValue(String(describing: newAvailableQuantity))
                        ref.child("Continent").child("Europe").child("Country").child("\(UserDetails.country!)").child("Region").child(UserDetails.region!).child("City").child(UserDetails.city!).child("Catalog").child("\(productId)").child("Sold Quantity").setValue(String(describing: newSoldQuantity))
                    }
                    //                }
                }
            }

        } catch  {
            print("Product.incrementIventory(): Error in fetching a product : \(error)")
        }
        do {
            try context.save()
            print("Product.incrementIventory(): modified product is saved to Core Data")
            completed(true)
        } catch  {
            print("Product.incrementIventory(): Error saving modified product to Core Data : \(error)")
        }
    } 

1 个答案:

答案 0 :(得分:0)

经过多次尝试,我终于找到了问题所在。我更改了观察者,也将Order实体的子实体的CoreData删除规则从“层叠”更改为“无效”。我将其重新设置为“级联”,现在一切又可以正常工作了。我可以将其范围缩小到仅仅因为保存功能正常工作,而删除功能导致了错误。 我将不得不研究“ nullify”的正确用法以及它为什么破坏了我的代码。 如果您有任何想法,我将非常感谢。
感谢您的帮助。