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
而崩溃。
过去几天我一直试图修复它,尝试不同的方式,但没有用。我在这做什么错?
答案 0 :(得分:0)
你能试试这段代码吗?
let bgContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
bgContext.persistentStoreCoordinator = appDelegate.coreData.persistentContainer.persistentStoreCoordinator
并删除
let moc = appDelegate.coreData.persistentContainer.viewContext
bgContext.parent = moc