Skip to content

Instantly share code, notes, and snippets.

@mxswd
Created March 10, 2022 07:54
Show Gist options
  • Save mxswd/7953635e75592c1bb2d420d1df0e199e to your computer and use it in GitHub Desktop.
Save mxswd/7953635e75592c1bb2d420d1df0e199e to your computer and use it in GitHub Desktop.
Persisting stuff. In the MyModel.xcdatamodel make an Entity called MyThingEntity, an attribute index with type int32, an attribute data with type Data. Give the entity a constraint on the index.
import UIKit
import CoreData
public struct MyThing: Codable {
var state: Bool? = nil
var value: String? = nil
}
class ViewController: UIViewController, UITextViewDelegate {
@IBOutlet weak var toggleSwitch: UISwitch!
@IBOutlet weak var textView: UITextView!
var context: NSManagedObjectContext!
var thing1: MyThingEntity!
var thing2: MyThingEntity!
override func viewDidLoad() {
super.viewDidLoad()
let container = NSPersistentContainer(name: "MyModel")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
context = container.viewContext
let things = (try! context.fetch(NSFetchRequest<MyThingEntity>(entityName: "MyThingEntity")))
if things.isEmpty {
thing1 = MyThingEntity(context: context)
thing1.index = 0
thing1.data = try! JSONEncoder().encode(MyThing())
thing2 = MyThingEntity(context: context)
thing2.index = 1
thing2.data = try! JSONEncoder().encode(MyThing())
} else {
thing1 = things.first
thing2 = things.last
}
textView.delegate = self
textView.text = (try! JSONDecoder().decode(MyThing.self, from: thing1.data!)).value
}
@IBAction func doAToggle(_ sender: Any) {
var entity: MyThingEntity
if toggleSwitch.isOn {
entity = thing1
} else {
entity = thing2
}
textView.text = (try! JSONDecoder().decode(MyThing.self, from: entity.data!)).value
}
func textViewDidChange(_ textView: UITextView) {
var entity: MyThingEntity
if toggleSwitch.isOn {
entity = thing1
} else {
entity = thing2
}
var thing = (try! JSONDecoder().decode(MyThing.self, from: entity.data!))
thing.value = textView.text
entity.data = try! JSONEncoder().encode(thing)
try! context.save()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment