当尝试在完成处理程序 - Swift4中更新时,CoreData获取的对象变为nil

时间:2018-05-28 05:19:32

标签: ios core-data entity swift4 nsmanagedobject

        let bgContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)

        let moc = appDelegate.coreData.persistentContainer.viewContext
        bgContext.parent = moc
        bgContext.perform({

            let fetchedResultController: NSFetchedResultsController<ReservationsEntity>
            let request: NSFetchRequest<ReservationsEntity> = ReservationsEntity.fetchRequest()
            let sort = NSSortDescriptor(key: #keyPath(ReservationsEntity.reservedDate), ascending: true)
            request.sortDescriptors = [sort]
            request.predicate = NSPredicate(format: "isSynced == %@", NSNumber(value: false))
            fetchedResultController = NSFetchedResultsController(fetchRequest: request, managedObjectContext: moc, sectionNameKeyPath: nil, cacheName: nil)

            do{
                try fetchedResultController.performFetch()
                for reservationEntity in fetchedResultController.fetchedObjects!{

                    print(reservationEntity.isSynced!)
                    let params = BaseViewController.getReservationDictionaryForOffline(reservation: reservationEntity)
                    ServerCalls.addReservationToServer(parametersForReservation: params, kindOfScreen: 0, completionHandler: { (response) in
                        print(reservationEntity.isSynced!)

                        reservationEntity.isSynced = true

                    })
                }

            } catch{

            }


        })

问题:您好!我有一个用例AddReservation,其中我将一条记录添加到名为ReservationsEntity的CoreData Entity,其属性为isSynced到{{ 1}}最初。我也同时进行服务器调用,一旦服务器调用返回,我试图将标志false更新为isSynced。但在服务器调用返回后,我的CoreData对象变为零。

根据上面发布的代码,首先true在调试器中显示print(reservationEntity.isSynced!)。当我在false返回后尝试打印/访问reservationEntity时,应用会因ServerCalls.addReservationToServer对象变为reservationEntity而崩溃。

过去几天我一直试图修复它,尝试不同的方式,但没有用。我在这做什么错?

1 个答案:

答案 0 :(得分:0)

你能试试这段代码吗?

let bgContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
bgContext.persistentStoreCoordinator = appDelegate.coreData.persistentContainer.persistentStoreCoordinator

并删除

let moc = appDelegate.coreData.persistentContainer.viewContext
bgContext.parent = moc