When I'm trying to delete objects from my core data I get this error:
fatal error: NSArray element failed to match the Swift Array Element type
and I have to idea why this happens. My table view is divided into sections, maybe that has something to do with it? I have never had any problem with deleting core-data from a table view before, so this is very strange to me.
My code looks like this:
var userList = [User]()
var usernames = [String]()
viewDidLoad(){
let appDel:AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let context:NSManagedObjectContext = appDel.managedObjectContext!
let fetchReq = NSFetchRequest(entityName: "User")
let en = NSEntityDescription.entityForName("User", inManagedObjectContext: context)
let sortDescriptor = NSSortDescriptor(key: "username", ascending: true)
fetchReq.sortDescriptors = [sortDescriptor]
fetchReq.propertiesToFetch = ["username"]
fetchReq.resultType = .DictionaryResultType
userList = context.executeFetchRequest(fetchReq, error: nil) as [User]
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
let editedCell = self.tv.cellForRowAtIndexPath(indexPath)
let appDel:AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let context:NSManagedObjectContext = appDel.managedObjectContext!
if editingStyle == UITableViewCellEditingStyle.Delete {
if let tv = tableView as Optional{
let textLbl = editedCell?.textLabel?.text
let ind = find(usernames, textLbl!)! as Int
context.deleteObject(userList[ind] as NSManagedObject)
userList.removeAtIndex(ind)
tv.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Fade)
}
}
}
In my code, the usernames array is just an array with all the usernames retrieved from core data in userList.
The errors appears last in my code where I'm trying to delete the object from the context, and from the userList; it's the same error in both lines. I've tried casting my userList as Array<AnyObject> but then I also got an runtime error with zero clues to what was wrong.
Any suggestions on how to solve this issue would be very appreciated.