索引超出范围问题

时间:2018-01-29 11:44:37

标签: ios swift uitableview

我在一个tableview中有一些项目如此显示......

enter image description here

如果单击Add To Cart按钮,则单元格中的特定数据将显示在另一个视图中,如此...

enter image description here

但是在第一个tableview中,如果单击最后一个删除按钮(与名称dddd关联),则应该从第二个屏幕中删除它。但它崩溃说index out of range可能是因为在第二个屏幕中,名称dddd的索引是1,而在第一个屏幕中它的索引是2.这是删除操作的代码...

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 { }

1 个答案:

答案 0 :(得分:1)

您的应用程序崩溃是因为您有两个数组cartDetailsnewProdDetails,并且两者都有不同的索引。现在的情况是,不同阵列中同一对象的索引不可能相同。

cartDetails有两个项目,分别为0和ddd为1

newProdDetails有三个项目,分别为0,fgh为1,ddd为2

现在认为newProdDetails indexPath.row ddd中的cartDetails是2,如果您在productID上搜索未找到的相同索引,则&gt;崩溃

建议:

这样的第一个Fetch对象,其中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 } 字段不是名称字段(如果您的实体中没有它,请添加它)

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

            }) {

 }

以下是搜索索引的示例

<template>
  <div>
    <input type="text" v-model="input_one">
    <component-two :secondValue.sync="input_two"></component-two>
  </div>
</template>

<script>
  import ComponentTwo from 'component-two.vue'

  export default {
    name: "component-one",
    components: {
      ComponentTwo
    },
    data() {
      return {
        input_one: 'Hello from ComponentOne',
        input_two: ''
      }
    }
  }
</script>

希望它对你有所帮助