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{
}
})
Issue : Hello!I have a use case saying AddReservation
where I add a record to CoreData Entity named ReservationsEntity
with an attribute isSynced
to false
initially. I also make a server call simultaneously and once the server call returns, I am trying to update the flag isSynced
to true
. But after the server call returns my CoreData object is becoming nil.
As per the code posted above, first print(reservationEntity.isSynced!)
shows false
in the debugger. When I try to print/ access reservationEntity
after ServerCalls.addReservationToServer
returns, app crashes as the reservationEntity
object becomes nil
.
I have been trying to fix it for the past few days trying different ways but of no use. What's the mistake I am doing here?
Can you try this code
let bgContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
bgContext.persistentStoreCoordinator = appDelegate.coreData.persistentContainer.persistentStoreCoordinator
And remove
let moc = appDelegate.coreData.persistentContainer.viewContext
bgContext.parent = moc
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.