I have created a Coredatacontroller class which take care of all Core data operations. One method to get the current context is written in this class.
func getCurrentContext() -> NSManagedObjectContext {
var curMOC:NSManagedObjectContext? = self.managedObjectContext
let thisThread:Thread = Thread.current
print("This thread: ", thisThread)
if thisThread == Thread.main {
if curMOC != nil {
return curMOC!
}
let coordinator:NSPersistentStoreCoordinator? = self.persistentStoreCoordinator
if coordinator != nil {
curMOC = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.mainQueueConcurrencyType)
curMOC?.persistentStoreCoordinator = coordinator
}
return curMOC!
}
// if this is some other thread....
// Get the current context from the same thread..
var threadManagedObjectContext:NSManagedObjectContext? = thisThread.threadDictionary.object(forKey:"MOC_KEY") as? NSManagedObjectContext;
// Return separate MOC for each new thread
if threadManagedObjectContext != nil {
return threadManagedObjectContext!;
}
let coordinator:NSPersistentStoreCoordinator? = self.persistentStoreCoordinator
if coordinator != nil {
threadManagedObjectContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.privateQueueConcurrencyType)
threadManagedObjectContext?.persistentStoreCoordinator = coordinator
threadManagedObjectContext?.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
thisThread.threadDictionary.setObject(threadManagedObjectContext!, forKey: "MOC_KEY" as NSCopying)
}
return threadManagedObjectContext!;
}
I am using NSOperation subclass to upload some images so for each image an object of NSOperation is being made. Inside completion block of NSOperation I am fetching some data from CoreData and update that.
Problem: Fetching doesn't return records that is present in core data If in fetching method i use mainmanagedobjectcontext then i get the record but when i am saving it with currentcontext it doesn't reflect changes to core data. I had written notification observer method also in NSOperation subclass but that method never get called. Please suggest what should be done !!
currentContext
? Explain what you're trying to achieve instead of how. What iOS version are you targeting? Do you know aboutNSPersistentContainer
? cocoacasts.com/… – Lukasmoc
lazily in yourOperation
subclass, get rid-off thegetCurrentContext
and instead access the context as:operation.block(completion: {_ in operation.moc })
. Assuming you're reading usingviewContext
, setviewContext.automaticallyMergesChangesFromParent = true
inloadPersistentStores
completion handler. I might be able to give you a full answer if you reply the rest of my questions in the comment. – Lukas