Skip to content

Instantly share code, notes, and snippets.

@crazytonyli
Created February 15, 2023 09:40
Show Gist options
  • Save crazytonyli/d37b579959184c15c4174253bdf83f28 to your computer and use it in GitHub Desktop.
Save crazytonyli/d37b579959184c15c4174253bdf83f28 to your computer and use it in GitHub Desktop.
Update in another context
// To run this code:
// 1. Create a macOS playground from Xcode.
// 2. Copy below code into the playground.
// 3. Click the Run button to see the console output.
import Foundation
import CoreData
func createObjectModel() -> NSManagedObjectModel {
let nameAttr = NSAttributeDescription()
nameAttr.name = "username"
nameAttr.type = .string
let nameProp = NSPropertyDescription()
nameProp.name = "username"
let user = NSEntityDescription()
user.name = "User"
user.properties = [nameAttr]
let model = NSManagedObjectModel()
model.entities = [
user
]
return model
}
let container = NSPersistentContainer(name: "Test", managedObjectModel: createObjectModel())
container.persistentStoreDescriptions = [
NSPersistentStoreDescription(url: URL(filePath: "/dev/null"))
]
container.loadPersistentStores { _, _ in }
let viewContext = container.viewContext
viewContext.automaticallyMergesChangesFromParent = true
let user = NSEntityDescription.insertNewObject(forEntityName: "User", into: viewContext)
user.setValue("Foo", forKey: "username")
try viewContext.save()
let background = container.newBackgroundContext()
try background.performAndWait {
let user = try background.existingObject(with: user.objectID)
user.setValue("Bar", forKey: "username")
try background.save()
}
print(user.value(forKey: "username"))
DispatchQueue.main.async {
print(user.value(forKey: "username"))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment