Created
March 10, 2022 07:54
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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