I'm not exactly sure what's going on with this, but I could use some help. I'm attempting to perform a query in the background every time a user enters text into a UITextField. I've been reading around and it looks like this is how I should be performing background CoreData operations, but I keep getting this error:
"Can only use -performBlock: on an NSManagedObjectContext that was created with a queue"
I googled this error, but every solution was saying that my context needs to be created using the PrivateQueueConcurrentcyType, which I did. Not sure why this is happening. Maybe it's a bug in the new iOS?
let managedObjectContext = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = appDelegate.persistentStoreCoordinator
if !textField.text.isEmpty {
manatedObjectContext.performBlock {
let objectIDs = //query to get the object IDs
appDelegate.managedObjectContext.performBlock {
var objects = Object[]()
for id in objectsIDs {
objects += appDelegate.managedObjectContext.objectWithID(id) as Object
}
self.searchResults = objects
self.searchResultsTableView.reloadData()
}
}
}
EDIT: I fixed my issue by doing the following:
- Setting the parent context for private managedObjectContext as my main context from the AppDelegate
- I removed the line that sets the persistent store because it's no longer needed when setting the parent context as the main context
- I also changed default implementation for creating the main context to explicitly create it using MainQueueConcurrencyType
managedObjectContext.psc = appDelegate.psc
. You probably should make yourthreadMOC
depend on yourmainMOC
using-setParentContext:
instead. See my complete example below. – SwiftArchitect