UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Error when deleting from CoreData

Forums > SwiftUI

I get this error when deleting from CoreData" Thread 1: "*** -[__NSArray0 objectAtIndex:]: index 0 beyond bounds for empty NSArray"

 ScrollView{
            LazyVGrid(columns: gridItemLayot,spacing: 2){
                ForEach(items.indices){ index in
                    NavigationLink(destination: ImageView(del: items[index])){
                        ZStack(alignment: .topTrailing){
                            Image(uiImage: UIImage(data: items[index].post_pic!)!)
                                .resizable()
                                .frame(width: 120, height: 120)
                                .font(.system(size: 30))
                                .cornerRadius(5)
                                .padding(.bottom,7)
                            if isEditing == true{
                                Button(action:{
                                    removePost(offsets: [index])
                                    // vm.refresh()
                                }){
                                    Text("⛔️")
                                }.buttonStyle(PlainButtonStyle())
                                .offset(x:5,y:-5)

                            }
                        }
                    }
                }
            }

        }.onAppear(perform: {vm.refresh()})
    private func removePost( offsets: IndexSet) {
        withAnimation {
            offsets.map { items[$0] }.forEach(vm.viewContext.delete)
            do {
                try vm.viewContext.save()
            } catch {
                let nsError = error as NSError
                fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
            }
        }
    }

This function workes when I delete from List

3      

Don't use indices with a ForEach if your data is dynamic. That form of ForEach only reads the data once and doesn't update it as you add/delete items. So, in your case, ForEach reads that you have an array with (for example) 8 item when you first initialize it but then if you delete one so that you have 7 items it will still think you have 8 items and you will run into issues.

If your data is dynamic, you need to use a ForEach that identifies them either because the items conform to Identifiable or because you supply an explicit id parameter.

3      

Thank you, but how can I pass the current IndexSet to the function removePost(offsets: IndexSet)

        ScrollView{
                    LazyVGrid(columns: gridItemLayot,spacing: 2){
                        ForEach(items){ item in
                            NavigationLink(destination: ImageView(item: item)){
                                ZStack(alignment: .topTrailing){
                                Image(uiImage: UIImage(data: item.post_pic!)!)
                                    .resizable()
                                    .frame(width: 120, height: 120)
                                    .font(.system(size: 30))
                                    .cornerRadius(5)
                                    .padding(.bottom,7)
                                    Button(action:{

                                        removePost(offsets: [...])
                                    }){
                                        Text("⛔️")
                                    }
                                }
                            }
                        }
                    }

                }.onAppear(perform: {vm.refresh()})

3      

but how can I pass the current IndexSet to the function removePost(offsets: IndexSet)

You don't. The way you have it set up, you'll only ever be deleting one item at a time anyway, so pass the item itself to your delete method and then you can just delete it directly from your view context.

The method using an IndexSet is useful when you are using a List in edit mode and can select multiple items at once.

3      

Yes, I passed the item itself and it workes now, Thank you

 removePost(item: item)
    private func removePost(item: Post) {
        withAnimation {
            vm.viewContext.delete(item)

            do {
                try vm.viewContext.save()
            } catch {
                let nsError = error as NSError
                fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
            }
        }
    }

4      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.