【问题标题】:Core Data in iOS, index out of rangeiOS中的核心数据,索引超出范围
【发布时间】:2017-12-23 05:41:38
【问题描述】:

在我的应用程序中,我使用的是 Core Data,到目前为止一切正常。当我尝试更新条目时遇到问题。有趣的是,我可以更新实体中除地址字段之外的所有内容。我没有做任何不同的事情,但是当我尝试仅更新该字段并出现致命错误时应用程序崩溃:索引超出范围。这是实际实体的屏幕截图。

这只是一些客户信息,所有条目都是字符串。在我的编辑 vc 中,我使用了一个 var 来保存客户端信息、设置委托并使用了一些谓词。代码如下:

//This is declared right under the class
var myClientToEdit: NSManagedObject = NSManagedObject()

//my save button action
@IBAction func saveMyEdits(_ sender: Any)
{
    //get the delegate
    guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else
    {
        return
    }

    //get managedContext
    let managedContext = appDelegate.persistentContainer.viewContext

    //get the client's entry
    let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Clients")

    fetchRequest.returnsObjectsAsFaults = false

    //use predicates to make sure it is the client I need
    fetchRequest.predicate = NSPredicate(format: "lastName == %@", mylastName)
    fetchRequest.predicate = NSPredicate(format: "firstName == %@", myfirstName)
    fetchRequest.predicate = NSPredicate(format: "address = %@", myaddress)

    do {
        var myClientToEdit = try managedContext.fetch(fetchRequest)
        let myObject = myClientToEdit[0]

        //my correct client is printed
        print(myObject)

        //using new entries to set new values
        myObject.setValue(lastName.text!, forKey: "lastName")
        myObject.setValue(firstName.text!, forKey: "firstName")
        myObject.setValue(address.text!, forKey: "address")
        myObject.setValue(city.text!, forKey: "city")
        myObject.setValue(state.text!, forKey: "state")
        myObject.setValue(zip.text!, forKey: "zipCode")
        myObject.setValue(phoneDay.text!, forKey: "phoneDay")
        myObject.setValue(phoneEve.text!, forKey: "phoneEvening")
        myObject.setValue(email.text!, forKey: "email")

        do{
            //save
            try managedContext.save()
        }catch let error as NSError{
            print(error)
        }

    }catch let error as NSError {
        print(error)
    }

   //dismis upon saving edits 
    self.dismiss(animated: true, completion: nil)
}

当我回到我的详细客户端 vc 时,我会做同样的事情,但只是从 Core Data 中读取。这是详细客户端vc的代码。

override func viewWillAppear(_ animated: Bool)
{
    guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else
    {
        return
    }

    let managedContext = appDelegate.persistentContainer.viewContext

    let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Clients")

    fetchRequest.predicate = NSPredicate(format: "lastName == %@", myLastName)
    fetchRequest.predicate = NSPredicate(format: "firstName == %@", myFirstName)
    fetchRequest.predicate = NSPredicate(format: "address == %@", myAddress)

    do {
        var thisIsTheClient = try managedContext.fetch(fetchRequest)
        let myObject = thisIsTheClient[0]

        print(myObject)

        lastNameLabel.text = myObject.value(forKey: "lastName") as? String
        firstNameLabel.text = myObject.value(forKey: "firstName") as? String
        myCityLabel.text = myObject.value(forKey: "city") as? String
        myAddressLabel.text = myObject.value(forKey: "address") as? String
        myStateLabel.text = myObject.value(forKey: "state") as? String
        myZipLabel.text = myObject.value(forKey: "zipCode") as? String
        myDayLabel.text = myObject.value(forKey: "phoneDay") as? String
        myEveLabel.text = myObject.value(forKey: "phoneEvening") as? String
        myEmailLabel.text = myObject.value(forKey: "email") as? String 

    }catch let error as NSError
    {
        print(error)
    }
}

错误就行了:let myObject = thisIsTheClient[0]。但只有当我尝试编辑地址时。 thisIsTheClient 也在类下定义。我知道 index out of range 与尝试将某些东西放在数组中没有类似的地方有关,但我不明白为什么它只在我尝试编辑地址时才会这样做。所有其他条目都已完美更新。

编辑 7/19/17

感谢大家的回复! Maor 和 Jay 都有正确的谓词。我只是在客户端上搜索地址,而不是前三个属性。在 Jay 关于 var 的注释之后,我能够将新数据传回并更新 var 并搜索新记录。再次感谢!

【问题讨论】:

  • 你试过调试 SQL 操作吗?看起来您的带地址的 SQL 操作出现了一些错误。调试 SQL 操作编辑您的方案并在参数部分添加以下代码 -com.apple.CoreData.Logging.stderr 1
  • 您是否在已经存储了一些数据时添加了地址属性?
  • @Roy,是的,地址以及所有其他属性都有值。我正在编辑 vc 中重写它们
  • 如果是,那么您需要重置 Clients 的数据,然后您可以随时更新地址@Douglas

标签: ios swift core-data


【解决方案1】:

我认为您遇到的问题与您认为的不同。 首先,当你写的时候:

fetchRequest.predicate = NSPredicate(format: "lastName == %@", myLastName)
fetchRequest.predicate = NSPredicate(format: "firstName == %@", myFirstName)
fetchRequest.predicate = NSPredicate(format: "address == %@", myAddress)

只考虑最后一行,因为它会覆盖之前的任何内容,这意味着在您的情况下,它只会查找地址属性(我猜这就是为什么您认为您的问题仅在地址中场地..) 您应该按照 @Jay 为您提供的操作来获得复合谓词。

第二件事(如果我理解正确的话)是您将地址更改为 myAddressLabel.text 保存的任何文本,并保存了它。但是,当您从详细信息 vc 上读取核心数据时,您仍然尝试通过“myAdress”变量进行查询,该变量与您保存的变量不同。如果是这种情况,那么它解释了为什么您会收到此错误消息 - 它根本没有找到与您的搜索匹配的任何内容,因此当您尝试从空数组中获取第一个元素时,它会告诉您它已经超出界限...

【讨论】:

  • 谢谢!我按照你和 Jay 的建议修复了谓词。我什至不知道我错了!您关于变量的提示帮助我弄清楚我正在使用一些不正确的数据进行获取。 +1 来自我。仍然收到错误,但那是因为我正在搜索不再存在的记录。我只需要找到一种方法来更新正确的值。
【解决方案2】:

我相当肯定,为了组合谓词,您必须使用复合谓词,而不是仅仅尝试更改获取请求的属性:

let predicate1:NSPredicate = NSPredicate("label = 'foo'")
let predicate2:NSPredicate = NSPredicate("label = 'bar'")
let compound:NSCompoundPredicate = NSCompoundPredicate(andPredicateWithSubpredicates: [predicate1,predicate2])

【讨论】:

  • 谢谢,我会调查的。
  • 嗯,成功了!我什至没有注意到搜索和谓词的那个方面。 +1 来自我。虽然双等号似乎和单等号没什么区别?谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-09-30
  • 1970-01-01
  • 2018-03-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多