user8894520
user8894520

Reputation:

Index out of range issue

I have some items in one tableview shown like so...

enter image description here

If the Add To Cart button is clicked, then that particular data in cell is shown in another view like so..

enter image description here

But in the first tableview, if the last remove button (associated with the name dddd) is clicked, then it should be removed from the 2nd screen. But it crashes saying index out of range possibly because in the second screen the index of the name dddd is 1 and in the first screen its index is 2. This is the code of the remove action...

let context1 = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
            let request = NSFetchRequest<NSFetchRequestResult>(entityName: "CartProducts")

            let sdf1 = newProdDetails[indexPath.row]
            let dfg2 = sdf1.name

            let predicate = NSPredicate(format: "name == %@", dfg2!)
            request.predicate = predicate
            request.fetchLimit = 1

            do{
                let count = try context1.count(for: request)
                if(count == 0){
                    // no matching object
                }
                else{
                    // at least one matching object exists

                    context1.delete(self.cartDetails[indexPath.row] as NSManagedObject)
                    self.cartDetails.remove(at: indexPath.row) //crash occurs here
                    do {
                        try context1.save()
                    }
                }
            }catch let error as NSError { }

Upvotes: 0

Views: 120

Answers (1)

Prashant Tukadiya
Prashant Tukadiya

Reputation: 16466

You application crashes because you have two arrays cartDetails and newProdDetails and both has different indexes . now the case is there is no possibility that index of same object in different array is same.

i.e

cartDetails has two items asd at 0 and ddd at 1

while newProdDetails has three items asd at 0, fgh at 1, ddd at 2

now think in newProdDetails in indexPath.row of ddd is 2 and if you search same index on cartDetails which is not found --> CRASH

Suggestion:

First Fetch object like this with productID field not name field (add it if you don't have it in your entity)

let fetchRequest: NSFetchRequest< CartProducts> = CartProducts.fetchRequest()
fetchRequest.predicate = Predicate.init(format: "itemID==\(productID)")

// withID you will get in your object of  `CartProducts`

if let result = try? context.fetch(fetchRequest) {
    for object in result {
        context.delete(object) // Always a single object if found
    }
}

do {

    try context.save() // <- remember to put this :)
    // Here now you have to search `indexOf` of `ddd` to `cartDetails`  and delete it.
} catch { 
    // Do something... fatalerror
}

Here is example how to search index

if let index =   newProdDetails.index(where: { (object) -> Bool in
                return (object["productID"] as! Int) == 1

            }) {

 }

Hope it is helpful to you

Upvotes: 1

Related Questions