簡體   English   中英

當CoreData Swift中已存在記錄時,函數不返回

[英]Function is not returning when a record already exists in CoreData Swift

我有一個由firebase .childAdded observer調用的函數,我試圖在寫入之前檢查要寫入的記錄是否已在數據庫中。 這是因為當用戶登錄時,所有傳入的快照都將導致在數據庫中多次輸入。 我嘗試執行檢查的方式是對記錄.contains bool,如果它比函數應該返回,否則它將繼續並寫入新記錄,但不起作用,在每次登錄時它將添加全部傳入的快照。 我該怎么辦呢? 一如既往的感謝。 這是功能:

static func saveBooking(bookingId: String, bookingDate: String, bookingStart: String, bookingEnd: String, customerName: String, price: String, workList: String) throws {
        let context = CoreData.databaseContext

        let request: NSFetchRequest<User> = User.fetchRequest()
        do {
            let fetch = try context.fetch(request)
            print("@@@@@@@@@@@@@@@@@@       fetching user")

            for value in fetch {
                if value.name == UserDetails.fullName {
                    print("User is: \(value.name!)")  //correct


                    if #available(iOS 10.0, *) {
                        let booking = Booking(context: context)
                        booking.user?.name = value.name!

                        booking.bookingId = bookingId
                        booking.bookingDate = bookingDate
                        booking.bookingStart = bookingStart
                        booking.bookingEnd = bookingEnd
                        booking.customerName = customerName
                        booking.bookingPrice = price
                        booking.worksList = workList
                        if value.bookings!.contains(booking){
                            print("@@@@@@@@@   found existing record for this booking! ")
                            return

                        } else {
                            value.addToBookings(booking)
                            print("@@@@@@@@@@@@@@@@@@@@@@@@@  booking user at propertis value attribution is : \(String(describing: booking.user!.name!))")
                            do {
                                try context.save()
                                print("@@@@@@@@@@@@@@@@@@@@@@@@@  booking user after saving booking is : \(String(describing: booking.user!.name!))")
                                print("@@@@@@@@@@@@    New booking is saved")
                            } catch  {
                                print("@@@@@@@@@@@@@@    Error saving new booking")
                                print(error)
                            }
                        }

                    } else {
                        // Fallback on earlier versions
                        let entityDescription = NSEntityDescription.entity(forEntityName: "Booking", in: context)
                        let booking = Booking(entity: entityDescription!, insertInto: context)
                        booking.user?.name = value.name
                        booking.bookingId = bookingId
                        booking.bookingDate = bookingDate
                        booking.bookingStart = bookingStart
                        booking.bookingEnd = bookingEnd
                        booking.customerName = customerName
                        booking.bookingPrice = price
                        booking.worksList = workList
                        if value.bookings!.contains(booking) {
                            print("@@@@@@@@@   found existing record for this booking! ")
                            return
                        } else {
                            value.addToBookings(booking)
                            do {
                                try context.save()
                                print("@@@@@@@@@@@@    New booking is saved")
                            } catch  {
                                print("@@@@@@@@@@@@@@    Error saving new booking")
                                print(error)
                            }
                        }
                    }
                }
            }
        } catch  {
            print("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@      Error in fetching a user")
        }
    }

這行let booking = Booking(context: context)正在創建一個新的Booking並將其插入到上下文中。 這總是在發生(就像您患病之前一樣)。 這個新創建的Booking永遠不是value.booking集合的一部分-(怎么可能剛創建!)-因此總是添加它。

我想你想要的是

if value.bookings!.contains{ $0.bookingId == bookingId) {
    let booking = Booking(context: context)
    value.addToBookings(booking)
    booking.user?.name = value.name!
    ....

我最終使用NSFetchRequest<NSFetchResult>NSPredicate以更經典的方式對現有記錄進行檢查,但是我想了解如何使用和探索Jon Rose建議的解決方案,因為我當時確實非常有用。沒意識到我還是在創建一個新對象。
我希望這會幫助其他人。 因此該函數現在寫為:

static func saveBooking(bookingId: String, bookingDate: String, bookingStart: String, bookingEnd: String, customerName: String, price: String, workList: String) throws {
        let context = CoreData.databaseContext
        let request: NSFetchRequest<User> = User.fetchRequest()
        do {
            let fetch = try context.fetch(request)
            print("@@@@@@@@@@@@@@@@@@       fetching user")
            for userValue in fetch {
                if userValue.name == UserDetails.fullName {
                    print("User is: \(userValue.name!)")  //correct

                    let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Booking")
                    let predicate = NSPredicate(format: "bookingId == %@", bookingId)
                    request.predicate = predicate
                    request.fetchLimit = 1

                    do{
                        let count = try context.count(for: request)
                        if(count > 0){
                            //  matching object
                            print("@@@@@@@@@@@@ booking is already recorded")
                            return
                        }
                        else{
                            print("@@@@@@@@@@@@    booking is new")
                            if #available(iOS 10.0, *) {
                                let booking = Booking(context: context)
                                booking.user?.name = userValue.name!
                                booking.bookingId = bookingId
                                booking.bookingDate = bookingDate
                                booking.bookingStart = bookingStart
                                booking.bookingEnd = bookingEnd
                                booking.customerName = customerName
                                booking.bookingPrice = price
                                booking.worksList = workList
                                userValue.addToBookings(booking)
                            } else {
                                // Fallback on earlier versions
                                let entityDescription = NSEntityDescription.entity(forEntityName: "Booking", in: context)
                                let booking = Booking(entity: entityDescription!, insertInto: context)
                                booking.user?.name = userValue.name!
                                booking.bookingId = bookingId
                                booking.bookingDate = bookingDate
                                booking.bookingStart = bookingStart
                                booking.bookingEnd = bookingEnd
                                booking.customerName = customerName
                                booking.bookingPrice = price
                                booking.worksList = workList
                                userValue.addToBookings(booking)

                            }
                        }
                    }
                }
            }

            do {
                try context.save()
                print("@@@@@@@@@@@@    New booking is saved")
            } catch  {
                print("@@@@@@@@@@@@@@    Error saving new booking")
                print(error)
            }
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM