How to cancel a change made to a projectedValue - ios

So I have a view that allows a user to update a CoreData property.
They then have the option to cancel or save
The TextField is linked with the projectedValue of a CoreData class
TextField("New Value", text: $coreDataClass.value)
Its very nice that CoreData has been linked with Combine so that we can attach $ to get the two-way binding feature. However on this particular view is causing me some problems because if a user hits cancel after inserting any value then the value persists even after the view is dismissed.
How would I cancel the change if the user hits cancel... I thought using a lazy var would be perfect since its only read once but that didn't work. I thought about using a class to capture the initial value and then use it in the cancel method but that did not work either.
Any guidance on the issue would be greatly appreciated!
Answer for question in comment Unrelated
import SwiftUI
extension Text {
func buttonView(type: ButtonType) -> some View {
func selectColor(type: ButtonType) -> Color {
switch type {
case .default:
return .blue
case .destructive:
return .red
case .utility:
return .purple
}
}
return self.bold()
.foregroundColor(.white)
.padding(.horizontal)
.padding(.vertical, 5)
.background(selectColor(type: type))
.cornerRadius(8)
}
}
enum ButtonType {
case `default`
case destructive
case utility
}

As you may know, when you edit CoreData field, it's not getting saved to the database until you run viewContext.save().
In case you need to revert changes there's another one: viewContext.rollback()
But note, that it'll discard all changes made for all objects since the last save. So if you have many changes and wanna discard only a single one, you need to do it manually: in the init fill #State value with a value from your object field, and on Save write #State to your object field.

Related

How can I invalidate a SwiftUI View in response to a notification?

I'm new to SwiftUI and trying to start using it in a complex, existing UIKit app. The app has a theming system, and I'm not sure how to get the SwiftUI view to respond to theme change events.
Our theme objects look like
class ThemeService {
static var textColor: UIColor { get }
}
struct ViewTheme: {
private(set) var textColor = { ThemeService.textColor }
}
where the value returned ThemeService.textColor changes when the user changes the app's theme. In the UIKit portions of the app, views observe a "themeChanged" Notification and re-read the value of the textColor property from their theme structs.
I'm not sure how to manage this for SwiftUI. Since ViewTheme isn't an object, I can't use #ObservableObject, but its textColor property also doesn't change when the theme changes; just the value returned by calling it changes.
Is there a way to somehow get SwiftUI to re-render the view hierarchy from an external event, rather than from a change in a value that the view sees? Or should I be approaching this differently?
Your answer works perfectly well, but it requires adoption of ObservableObject. Here is an alternative answer which uses your existing NotificationCenter notifications to update a SwiftUI view.
struct MyView: View {
#State private var textColor: UIColor
var body: some View {
Text("Hello")
.foregroundColor(Color(textColor))
.onReceive(NotificationCenter.default.publisher(for: Notification.Name("themeChanged"))) { _ in
textColor = ThemeService.textColor
}
}
}
This requires a #State variable to hold the theme's current data, but it's correct because a SwiftUI view is really just a snapshot of what the view should currently display. It ideally should not reference data that is arbitrarily changed because it leads to data-sync problems like the question you asked. So in a SwiftUI view, it is problematic to write ThemeService.textColor directly within the body unless you are certain an update will always occur after it the theme gets changed.
I was able to get this working by cheating with the theming system a little and changing the ViewTheme to an object:
class ViewTheme: ObservableObject {
private(set) var textColor = { ThemeService.textColor }
init() {
NotificationCenter.default.addObserver(forName: Notification.Name("themeChanged"),
object: nil, queue: .main) { [weak self] _ in
self?.objectWillChange.send()
}
}
}
Now the view can mark it with #ObservedObject and will be re-generated when the "themeChanged" notification is fired.
This seems to be working great, but I'm not sure if there are non-obvious problems that I'm missing with this solution.

SwiftUI 4: navigationDestination()'s destination view isn't updated when state changes

While experiments with the new NavigationStack in SwiftUI 4, I find that when state changes, the destination view returned by navigationDestination() doesn't get updated. See code below.
struct ContentView: View {
#State var data: [Int: String] = [
1: "One",
2: "Two",
3: "Three",
4: "Four"
]
var body: some View {
NavigationStack {
List {
ForEach(Array(data.keys).sorted(), id: \.self) { key in
NavigationLink("\(key)", value: key)
}
}
.navigationDestination(for: Int.self) { key in
if let value = data[key] {
VStack {
Text("This is \(value)").padding()
Button("Modify It") {
data[key] = "X"
}
}
}
}
}
}
}
Steps to reproduce the issue:
Run the code and click on the first item in the list. That would bring you to the detail view of that item.
The detail view shows the value of the item. It also has a button to modify the value. Click on that button. You'll observe that the value in the detail view doesn't change.
I debugged the issue by setting breakpoints at different place. My observations:
When I clicked the button, the code in List get executed. That's as expected.
But the closure passed to navigationDestination() doesn't get executed, which explains why the detail view doesn't get updated.
Does anyone know if this is a bug or expected behavior? If it's not a bug, how can I program to get the value in detail view updated?
BTW, if I go back to root view and click on the first item to go to its detail view again, the closure passed to navigationDestination() get executed and the detail view shows the modified value correctly.
#NoeOnJupiter's solution and #Asperi's comment are very helpful. But as you see in my comments above, there were a few details I wasn't sure about. Below is a summary of my final understanding, which hopefully clarifies the confusion.
navigationDestination() takes a closure parameter. That closure captures an immutable copy of self.
BTW, SwiftUI takes advantage of property wrapper to make it possible to "modify" an immutable value, but we won't discuss the details here.
Take my above code as an example, due to the use of #State wrapper, different versions of ContentView (that is, the self captured in the closure) share the same data value.
The key point here is I think the closure actually has access to the up-to-date data value.
When an user clicks on the "Modify it" button, the data state changes, which causes body re-evaluted. Since navigationDestination() is a function in body, it get called too. But a modifier function is just shortcut to modifier(SomeModifier()). The actual work of a Modifier is in its body. Just because a modifier function is called doesn't necessarilly means the corresponding Modifier's body gets called. The latter is a mystery (an implementation detail that Apple don't disclose and is hard to guess). See this post for example (the author is a high reputation user in Apple Developer Forum):
In my opinion, it definitely is a bug, but not sure if Apple will fix it soon.
One workaround, pass a Binding instead of a value of #State variables.
BTW, I have a hypothesis on this. Maybe this is based on a similar approach as how SwiftUI determines if it recalls a child view's body? My guess is that it might be a design, instead of a bug. For some reason (performance?) the SwiftUI team decided to cache the view returned by navigationDestination() until the NavigationStack is re-constructed. As a user I find this behavior is confusing, but it's not the only example of the inconsistent behaviors in SwiftUI.
So, unlike what I had thought, this is not an issue with closure, but one with how modifier works. Fortunately there is a well known and robust workaround, as suggested by #NoeOnJupiter and #Asperi.
Update: an alternative solution is to use EnvironmentObject to cause the placeholder view's body get re-called whenever data model changes. I ended up using this approach and it's reliable. The binding approach worked in my simple experiments but didn't work in my app (the placeholder view's body didn't get re-called when data model changed. I spent more than one day on this but unfortunately I can't find any way to debug it when binding stopped working mysteriously).
The button is correctly changing the value. By default navigationDestination does't create a Binding relation between the parent & child making the passed values immutable.
So you should create a separate struct for the child in order to achieve Bindable behavior:
struct ContentView: View {
#State var data: [Int: String] = [
1: "One",
2: "Two",
3: "Three",
4: "Four"
]
var body: some View {
NavigationStack {
List {
ForEach(Array(data.keys).sorted(), id: \.self) { key in
NavigationLink("\(key)", value: key)
}
}
.navigationDestination(for: Int.self) { key in
SubContentView(key: key, data: $data)
}
}
}
}
struct SubContentView: View {
let key: Int
#Binding var data: [Int: String]
var body: some View {
if let value = data[key] {
VStack {
Text("This is \(value)").padding()
Button("Modify It") {
data[key] = "X"
}
}
}
}
}

How to manually reload any row in swiftUI

I wanted to create List in SwiftUI with following requirements:
Each row has some detail, and Toggle which represents its isEnabled status.
If someone enables or disables that toggle, then based on some logic, Either I have to allow its to be enabled, OR not allow it to be enabled OR allow it to be enabled, but have to disable other object from other row.
I have my ViewModel and Model as below
I have my model and View model as somewhat like this
class MyViewModel:ObservableObject{
#Published myObjArray:[MyObject]
....
}
class MyObject:Identifiable{
var id:..
var isEnabled:Bool
var title:...
....
....
}
As MyObject is used at multiple places in project, so, I dont want to touch It.
For implementing Toggle, we have to provide binding, so, I created one state object in its RowView and on enable and disable of that toggle, I get its event like this:
struct MyRowView: View {
var myObj:MyObject
#State var isEnabled: Bool
....
....
init(myObj:MyObject) {
self.myObj = myObj
self.isEnabled = myObj.isEnabled
}
var body: some View {
....
Toggle("", isOn: $isEnabled)
.labelsHidden()
.onChange(of: isEnabled) { value in
self.MyViewModelAsEnvironmentObject.toggleValueUpdated()
}
....
}
As value of isEnabled changes, I am passing that to above mentioned MyViewModel object, where it checks for some conflicts, if conflicting, I am showing some alert, asking user to to forcefully enable this or not, if he says yes, then I have to disable row in other row, if user says no, then I have to disable this row.
Question is, How I can reload individual cell to enable or disable given toggle in given rows? If I print value directly in Row, then it is updating properly, but here isEnabled variable is assigned when row initiated, now its not possible to change its value from view model.
How to deal with this situation?

SwiftUI selectable lists where selection variable is ordered

I'll keep it simple, I have a List with UUID identified items. This list is selectable, when EditMode() is entered user can tap items, and these get added to the selection variable:
And the selection variable is:
#State var selection = Set<UUID?>()
However, the issue is that I care about the order in which the items are selected. And in the selection array, the items are not updated in a FIFO or LIFO way, they seem to be random or perhaps it depends on the value of the UUID but the point is it doesn't conserve the order in which they are added.
I considered using a stack to keep track of what is added, but the List + selection combination in SwiftUI doesn't appear to have built in methods to inform of new additions e.g. UUID 1234 has been added. I can thing of "not clean" ways to make it work like iterating through the whole selection Set every time selection.count changes and add the "new item" to the stack but I wouldn't want to come down to that.
So after some research, the List constructor that enables selection in .editMode does specify that the selection variable has to be a Set and nothing but a Set:
public init(selection: Binding<Set<SelectionValue>>?, #ViewBuilder content: () -> Content)
So I decided to implement my own array that keeps track of the selection order. I'll show how in case it helps anyone, but it is quite rudimentary:
#State var selectedItemsArray=[UUID]()
...
List(selection: $selection) {
...
}
.onChange(of: selection) { newValue in
if newValue.count>selectedItemsArray.count {
for uuid in newValue {
if !selectedItemsArray.contains(uuid) {
selectedItemsArray.append(uuid)
break
}
}
}
if newValue.count<selectedItemsArray.count {
for uuid in selectedItemsArray {
if !newValue.contains(uuid) {
selectedItemsArray.remove(at: selectedItemsArray.firstIndex(of: uuid)!)
break
}
}
}
}

SwiftUI holding reference to deleted core data object causing crash

Im finding it impossible to use core data with SwiftUI, because as I pass a core data to a view observed object variable, the navigation link view will hold a reference to the object even after the view has disappeared, so as soon as I delete the object from context the app crashes, with no error messages.
I have confirmed this by wrapping the core data object variable into a view model as an optional, then set the object to nil right after the context delete action and the app works fine, but this is not a solution because I need the core data object to bind to the swift ui views and be the source of truth. How is this suppose to work? I seriously cannot make anything remotely complex with SwiftUI it seems.
I have tried assigning the passed in core data object to a optional #State, but this does not work. I cannot use #Binding because it's a fetched object. And I cannot use a variable, as swiftui controls require bindings. It only makes sense to use a #ObservedObject, but this cannot be an optional, which means when the object assigned to it gets deleted, the app crashes, because i cannot set it to nil.
Here is the core data object, which is an observable object by default:
class Entry: NSManagedObject, Identifiable {
#NSManaged public var date: Date
}
Here is a view that passes a core data entry object to another view.
struct JournalView: View {
#Environment(\.managedObjectContext) private var context
#FetchRequest(
entity: Entry.entity(),
sortDescriptors: [],
predicate: nil,
animation: .default
) var entries: FetchedResults<Entry>
var body: some View {
NavigationView {
List {
ForEach(entries.indices) { index in
NavigationLink(destination: EntryView(entry: self.entries[index])) {
Text("Entry")
}
}.onDelete { indexSet in
for index in indexSet {
self.context.delete(self.entries[index])
}
}
}
}
}
}
Now here is the view that accesses all the attributes from the core data entry object that was passed in. Once, I delete this entry, from any view by the way, it is still referenced here and causes the app to crash immediately. I believe this also has something to do with the Navigation Link initializing all destination view before they are even accessed. Which makes no sense why it would do that. Is this a bug, or is there a better way to achieve this?
I have even tried doing the delete onDisappear with no success. Even if I do the delete from the JournalView, it will still crash as the NavigationLink is still referencing the object. Interesting it will not crash if deleting a NavigationLink that has not yet been clicked on.
struct EntryView: View {
#Environment(\.managedObjectContext) private var context
#Environment(\.presentationMode) private var presentationMode
#ObservedObject var entry: Entry
var body: some View {
Form {
DatePicker(selection: $entry.date) {
Text("Date")
}
Button(action: {
self.context.delete(self.entry)
self.presentationMode.wrappedValue.dismiss()
}) {
Text("Delete")
}
}
}
}
UPDATE
The crash is taking me to the first use of entry in the EntryView and reads Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0).. thats the only message thrown.
The only work around I can think of is to add a property to the core data object "isDeleted" and set it to true instead of trying to delete from context. Then when the app is quit, or on launch, I can clean and delete all entries that isDeleted? Not ideal, and would prefer to figure out what it wrong here, as it appears I'm not doing anything different then the MasterDetailApp sample, which seems to work.
I basically had the same issue. It seems that SwiftUI loads every view immediately, so the view has been loaded with the Properties of the existing CoreData Object. If you delete it within the View where some data is accessed via #ObservedObject, it will crash.
My Workaround:
The Delete Action - postponed, but ended via Notification Center
Button(action: {
//Send Message that the Item should be deleted
NotificationCenter.default.post(name: .didSelectDeleteDItem, object: nil)
//Navigate to a view where the CoreDate Object isn't made available via a property wrapper
self.presentationMode.wrappedValue.dismiss()
})
{Text("Delete Item")}
You need to define a Notification.name, like:
extension Notification.Name {
static var didSelectDeleteItem: Notification.Name {
return Notification.Name("Delete Item")
}
}
On the appropriate View, lookout for the Delete Message
// Receive Message that the Disease should be deleted
.onReceive(NotificationCenter.default.publisher(for: .didSelectDeleteDisease)) {_ in
//1: Dismiss the View (IF It also contains Data from the Item!!)
self.presentationMode.wrappedValue.dismiss()
//2: Start deleting Disease - AFTER view has been dismissed
DispatchQueue.main.asyncAfter(deadline: .now() + TimeInterval(1)) {self.dataStorage.deleteDisease(id: self.diseaseDetail.id)}
}
Be safe on your Views where some CoreData elements are accessed - Check for isFault!
VStack{
//Important: Only display text if the disease item is available!!!!
if !diseaseDetail.isFault {
Text (self.diseaseDetail.text)
} else { EmptyView() }
}
A little bit hacky, but this works for me.
I encountered the same issue and did not really find a solution to the root problem. But now I "protect" the view that uses the referenced data like this:
var body: some View {
if (clip.isFault) {
return AnyView(EmptyView())
} else {
return AnyView(actualClipView)
}
}
var actualClipView: some View {
// …the actual view code accessing various fields in clip
}
That also feelds hacky, but works fine for now. It's less complex than using a notification to "defer" deletion, but still thanks to sTOOs answer for the hint with .isFault!
I have had the same issue for a while, the solution for me was pretty simple:
In the View where the #ObservedObject is stored I simply put this !managedObject.isFault.
I experienced this class only with ManagedObjects with a date property, I don't know if this is the only circumstance the crash verifies.
import SwiftUI
struct Cell: View {
#ObservedObject var managedObject: MyNSManagedObject
var body: some View {
if !managedObject.isFault {
Text("\(managedObject.formattedDate)")
} else {
ProgressView()
}
}
}
After some research online, it's clear to me that this crash can be caused by many things related to optionals. For me, I realized that declaring a non-optional Core Data attribute as an optional in the NSManagedObject subclass was causing the issue.
Specifically, I have a UUID attribute id in Core Data that cannot have a default value, but is not optional. In my subclass, I declared #NSManaged public var id: UUID. Changing this to #NSManaged public var id: UUID? fixed the problem immediately.
I had the same issue recently. Adding an entity property to the view fixed it.
ForEach(entities, id: \.self) { entity in
Button(action: {
}) {
MyCell(entity: entity)
}
}
To
ForEach(entities, id: \.self) { entity in
Button(action: {
}) {
MyCell(entity: entity, property: entity.property)
}
}
I suspect that the nullable Core Data entity is the cause of the issue, where as adding a non-nil property as a var (e.g, var property: String) fixed it
I have tried all previous solutions, none worked for me.
This one, worked.
I had my list like this:
List {
ForEach(filteredItems, id: \.self) { item in
ListItem(item:item)
}
.onDelete(perform: deleteItems)
private func deleteItems(offsets: IndexSet) {
//deleting items
This was crashing.
I modified the code to this one
List {
ForEach(filteredItems, id: \.self) { item in
ListItem(item:item)
}
.onDelete { offsets in
// delete objects
}
This works fine without crashing.
For heaven's sake, Apple!
A view modifier for this (based on conditional view modifiers):
import SwiftUI
import CoreData
extension View {
#ViewBuilder
func `if`<Transform: View>(
_ condition: Bool,
transform: (Self) -> Transform
) -> some View {
if condition {
transform(self)
} else {
self
}
}
}
extension View {
func hidingFaults(_ object: NSManagedObject) -> some View {
self.if(object.isFault) { _ in EmptyView() }
}
}
Having said that, it's worth checking you're performing CoreData operations asynchronously on the main thread, doing it synchronously can be a source of grief (sometimes, but not always).
Apple says this (and it works perfectly) :
The behavior you've reported is the result of a system bug, and should
be fixed in a future release. As a workaround, you can prevent the
race condition by wrapping your deletion logic in
NSManagedObjectContext.perform:
private func deleteItems(offsets: IndexSet) {
withAnimation {
viewContext.perform {
offsets.map { molts[$0] }.forEach(viewContext.delete)
do {
try viewContext.save()
} catch {
viewContext.rollback()
userMessage = "\(error): \(error.localizedDescription)"
displayMessage.toggle()
}
}
}
You can find the full thread here https://developer.apple.com/forums/thread/668299
For me, I got this because of a force-unwrapped binding.
I used a Binding($item.someProperty)! like this: TextField("Description", text: Binding($item.someProperty)!).
This was because item is a Core Data class and hence someProperty is a String? instead of a String. Binding(*)! was a solution proposed in https://stackoverflow.com/a/59004832.
I changed the implementation to use a null coalescing operator for bindings as proposed in https://stackoverflow.com/a/61002589, now it doesn't crash anymore.
Wrap your deletion logic in a withAnimation block to prevent a crash after deleting a Core Data object. No need for isFault, isDeleted, or deferring execution in other complicated ways.
withAnimation {
context.delete(object)
do try catch etc...
}

Resources