Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save atomicbird/56e1b3852656541dd9b8ded99bb93445 to your computer and use it in GitHub Desktop.
Save atomicbird/56e1b3852656541dd9b8ded99bb93445 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
// Build a simple model in code for demo purposes.
// The model has a single entity called "Entity" with a single optional string attribute called "testAttribute".
// There are no relationships in the model.
let model = NSManagedObjectModel()
let entity = NSEntityDescription()
entity.name = "Entity"
let testAttribute = NSAttributeDescription()
testAttribute.name = "testAttribute"
testAttribute.attributeType = .stringAttributeType
testAttribute.isOptional = true
entity.properties = [testAttribute]
model.entities = [entity]
print("Model: \(model)")
let container = NSPersistentContainer(name: "TestModel", managedObjectModel: model)
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