ios - 从 Core Data Swift 中删除值时出现错误 Domain=NSCocoaErrorDomain Code=1570

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

我得到了

Error Domain=NSCocoaErrorDomain Code=1570 "The operation couldn’t be completed. (Cocoa error 1570.)"

两个曾经正常工作的函数出现错误。

第一个 deleteOrder() 是由 Firebase 观察者调用的函数。为了解决离线设备问题,我更改了已删除条目的逻辑,从简单地删除它们,改为将它们扭动到专用的“Deleted Orders”节点中,并在将观察者从 .childRemoved 更改后"Orders" 节点上的 childAdded"Deleted Orders" 节点上我说收到此错误。 deleteOrder() 没有改变,但现在 CoreData 在保存时抛出错误。据我所知并发现 (Cocoa error 1570.) 是关于保存到 CoreData 时缺少一些非可选参数,正如我之前使用 saveOrder( ) 函数,但是从 CoreData 删除时我无法解释它。

在收到订单或订单取消时,我也仅从两个保持库存更新的函数之一得到相同的错误。 decrementInventory() 在接收新订单时工作正常,但 incrementInventory() 在接收订单取消时抛出 (Cocoa 错误 1570。)。你能帮我找出错误在哪里吗?我一直在研究 decrementInventory()incrementInventory() 之间的代码差异,但它们以相反的方式执行完全相同的操作。

一如既往地感谢您的时间和帮助。

功能是:

Firebase 观察者:

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)")
            }
        })
    }

删除订单():

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")
        }
    }

incrementInventory():

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)")
        }
    } 

以及正确工作的decrementInventory():

static func decrementIventory(completed: @escaping (Bool) -> (), productId: String) throws {
        print("Product.decrementIventory() : 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.decrementIventory() : 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.decrementIventory() : Error in fetching a product : \(error)")
        }
        do {
            try context.save()
            print("Product.decrementIventory() : modified product is saved to Core Data")
            // setting completion for decrementIventory() here causes inconsistency in Firebase, so we set completion for decrementIventory() in Firebase.uploadProduct completed scope
                        completed(true)
        } catch  {
            print("Product.decrementIventory() : Error saving modified product to Core Data : \(error)")
        }
    }

最佳答案

经过多次尝试,终于找到了问题所在。我更改了观察者,我还将 Order 实体的子实体的 CoreData 删除规则从“cascade”更改为“nullify”。我已将其设置回“级联”,现在一切都恢复正常了。我可以将范围缩小到这个范围,因为保存功能正常工作,但删除功能导致了错误。 我必须调查“无效”的正确使用以及它破坏我的代码的原因。 如果您对此有任何想法,我将非常感激。
谢谢你帮我。

关于ios - 从 Core Data Swift 中删除值时出现错误 Domain=NSCocoaErrorDomain Code=1570,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56791349/

相关文章:

ios - Swift iOS 项目在创建空项目后立即泄漏

ios - 测试特定 iPhone 是否支持扩展模式下的分割 View

firebase - Flutter如何根据特定值对firebase中的列表进行分组

ios - Firebase 真实数据库数据获取

ios - 使用 SVN 修复 Xcode 中的重复工作副本

iphone - 更改图标/产品名称和图像 iPhone

ios - 当 NSDate 为 nil 时,NSDateFormatter 返回(空)字符串

arrays - 在 TableView 中过滤二维数组以在 Swift 中进行搜索

objective-c - 电子表格网格的 NSCell vs NSView?

启用 Firebase DB 持久性后,Swift 3 发现 nil