Reputation: 187
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
Reputation: 90117
Your fetch code is wrong. Here are the principles of the executeFetchRequest
method:
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