I'm getting a Index Beyond Bounds
error and a Thread 1: EXC_BAD_ACCESS (code=EXC_I386_GPFLT)
when trying to delete a Core Data index in SwiftUI.
Basically, I have a Core Data entity (Dates
), containing only a date
attribute (Constraint - String). This has a one-to-many relationship with my Records
Entity. I am trying to display a list of all date
's I have. Displaying is fine, but upon trying to delete it, my app crashes.
My View currently looks as following:
import SwiftUI
struct Settings: View {
@Environment(\.managedObjectContext) var managedObjectContext
@FetchRequest(entity: Dates.entity(), sortDescriptors: []) var dates: FetchedResults<Dates>
var body: some View {
VStack {
List{
ForEach(dates, id: \.self) { day in
Text("\(day.wrappedDate)")
}.onDelete { (indexSet) in
let dateToDelete = self.dates[indexSet.first!]
self.managedObjectContext.delete(dateToDelete)
do {
try self.managedObjectContext.save()
} catch {
print(error)
}
}
}
}
}
}
I've broken my view down to the bare minimum to see if that would help, but unfortunately not.
When trying to delete. The error I get in the output is:
2020-04-29 16:08:23.980755+0300 TESTTEST[28270:2245700] [General] *** -[__NSArray0 objectAtIndex:]: index 0 beyond bounds for empty NSArray
If I have say 9 dates, it would say index 8 beyond bounds [0 .. 7]
, so it's not necessarily related to an empty Array.
Further output is:
=== AttributeGraph: cycle detected through attribute X ===
a bunch of times, followed by:
Thread 1: EXC_BAD_ACCESS (code=EXC_I386_GPFLT)
on my AppDelegate.
Could the issue be in generating the view - rather than the delete?
Please be aware that I'm a self-taught, absolute Noob when it comes to coding, so I might be missing something obvious here. Any help on getting to the answer myself in the form of instructions would also be greatly appreciated (so I can learn how to fix this).
EDIT:
I think I found out what's causing the issue. In another view I'm also generating a list of all date
s , where I apply an index on Dates
. Will amend code now to see if this fixes it....
TBC!
In a separate view I was calling a list of dates in the following way:
ForEach(0 ..< self.dates.count, id: \.self) { index in
Text("\(self.dates[index].date)")
}
Deleting one of the Date entities, would mess up the indices presented in this view. Changing this structure to the below fixed the issue:
ForEach(self.dates, id: \.self) { day in
Text("\(day.date)")
}