Skip to content

Instantly share code, notes, and snippets.

  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
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"
let testAttribute = NSAttributeDescription() = "testAttribute"
testAttribute.attributeType = .stringAttributeType
testAttribute.isOptional = true = [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")
// 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
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