Search code examples
swiftcore-dataios8nsmanagedobjectcontext

Delete a Core Data stack without using -lock method


The Core Data ManagedObjectContext -lock method is deprecated in iOS 8. However, until today, I've been able to write the following code in order to delete my Core Data Stack without having any warning:

// Delete Core Data stack
if let PSC = managedObjectContext.persistentStoreCoordinator {
    if let PS = PSC.persistentStores.first as? NSPersistentStore {
        let storeURL = PSC.URLForPersistentStore(PS)

        managedObjectContext.lock()
        managedObjectContext.reset()

        var error: NSError?
        if !PSC.removePersistentStore(PS, error: &error) {
            println("Unresolved error \(error), \(error!.userInfo)")
            abort()
        }
        if !NSFileManager.defaultManager().removeItemAtURL(storeURL, error: &error) {
            println("Unresolved error \(error), \(error!.userInfo)")
            abort()
        }
        if PSC.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeURL, options: nil, error: &error) == nil {
            println("Unresolved error \(error), \(error!.userInfo)")
            abort()
        }

        managedObjectContext.unlock()
    }
}

With Xcode 6.3 and Swift 1.2, I now get a warning with the following lines:

self.managedObjectContext.lock()
self.managedObjectContext.unlock()

'lock()' was deprecated in iOS version 8.0: Use a queue style context and -performBlockAndWait: instead

How to rewrite the previous code without using the -lock method? I just can't see how a -performBlockAndWait: can replace it.


Solution

  • I don't often need to remove a persistent store like that, but in principle I don't see why performBlockAndWait: wouldn't work. All that method does is ensure that the code in the block runs on the context's serial queue, whether a private queue or the main queue. It should be exactly as effective as calling lock used to be, if you are making sure to use block-style calls everywhere that you might access the context.