Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save AndrewBennet/97ca0686cbae6902aabeda502243557b to your computer and use it in GitHub Desktop.
Save AndrewBennet/97ca0686cbae6902aabeda502243557b to your computer and use it in GitHub Desktop.
A Swift playground demonstrating that deleting an NSManagedObject causes a fault to fire
import CoreData
import PlaygroundSupport
// Requires a momd called "TestModel" be added to the Resources directory of the playground.
// This can be obtained by creating a model in an iOS app, building, and copying the momd directory
// from the resulting Products directory into this playground's Resources directory.
// The model has a single entity called "Entity" with a single optional string attribute called "testAttribute".
// There are no relationships in the model.
let container = NSPersistentContainer(name: "TestModel")
container.loadPersistentStores{ _,_ in
// Create a new entity, save the model and reset the context
let context = container.viewContext
let entity = NSEntityDescription.insertNewObject(forEntityName: "Entity", into: context)
entity.setValue("test", forKey: "testAttribute")
try! context.save()
context.reset()
// Now try to fetch the existing entity. We want to delete it without firing the fault
let f = NSFetchRequest<NSManagedObject>(entityName: "Entity")
f.includesPropertyValues = false
f.fetchLimit = 1
// Get the first result from the fetch. This will be a fault
let firstEntity = try! context.fetch(f).first!
print("Entity is fault: \(firstEntity.isFault)")
// Delete the object. It will no longer be a fault
context.delete(firstEntity)
print("Entity is fault: \(firstEntity.isFault)")
}
PlaygroundPage.current.needsIndefiniteExecution = true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment