Claus Machholdt
Claus Machholdt

Reputation: 187

Check Core Data for existing data. Fatal error: cannot index empty buffer

I want to store a Username in Core Data. This means that I need to check whether the username exists in core data before saving the username there. I recieve an error, and can't seem to find a viable way to do this check. The error messaage is: "Cannot index empty buffer and happens

@objc func getCoreData()
{
    let fetchRequest = NSFetchRequest(entityName: "LoginDetails")
    var error: NSError? = nil
    if let fetchResults = managedObjectContext!.executeFetchRequest(fetchRequest, error: &error) as? [LoginDetails]
    {
        if (error != nil)
        {
            println("Error")
        }
        if true
        {
            setLoginDetails(fetchResults[0])
        }
    }
}

Upvotes: 0

Views: 78

Answers (1)

Matthias Bauch
Matthias Bauch

Reputation: 90117

Your fetch code is wrong. Here are the principles of the executeFetchRequest method:

  • it returns nil if there is an error
  • if it does not return nil there was no error
  • a fetch without matching objects returns an empty array. An empty fetch is not an error.

You should use something like this:

if let fetchResults = managedObjectContext!.executeFetchRequest(fetchRequest, error: &error) as? [LoginDetails]
{
    if countElements(fetchResults) > 0 {
        // at least 1 matching object found
        setLoginDetails(fetchResults[0])
    }
    else {
        // empty fetch. No matching objects found
    }
}
else {
    fatalError("Can't fetch \(error)")
}

Upvotes: 1

Related Questions