删除核心数据中的对象,无法匹配Swift数组元素types
当我试图从我的核心数据删除对象,我得到这个错误:
fatal error: NSArray element failed to match the Swift Array Element type
我必须明白为什么会发生这种情况。 我的表格视图被分成几个部分,也许和它有关系? 我从来没有从表视图中删除核心数据的任何问题,所以这是很奇怪的。
我的代码如下所示:
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) } } }
在我的代码中, usernames
数组只是一个数组,其中所有用户名都是从userList
核心数据中检索的。
错误出现在我的代码,我试图从context
,从userList
删除对象的最后一个; 这两条线都是一样的错误。 我已经尝试将我的userList
作为Array<AnyObject>
但是我也遇到了一个运行时错误,并提供了一些错误的线索。
任何build议如何解决这个问题将非常感激。
同
fetchReq.resultType = .DictionaryResultType
取回请求
userList = context.executeFetchRequest(fetchReq, error: nil) as [User]
返回一个NSDictionary
对象的数组,而不是一个User
对象的数组,并且你只是将编译器用cast转换as [User]
。
出于性能方面的原因,Swift运行时在这一点上不validation所有的数组元素是否都是User
对象,所以这个赋值是成功的。 但只要你访问一个数组元素,例如与
userList[ind]
那么你会得到运行时exception,因为元素types( NSDictionary
)不匹配数组types( User
)。
你也不能将字典转换回被pipe理的对象,所以这将永远不会工作:
context.deleteObject(userList[ind] as NSManagedObject)
最好的解决scheme可能只是删除线
fetchReq.propertiesToFetch = ["username"] fetchReq.resultType = .DictionaryResultType
以便获取请求返回一个User
对象数组,并在必要时调整其余的代码。
您可以再次查看https://stackoverflow.com/a/28055573/1187415中提出的两种不同的解决scheme。 第一个返回一个托pipe对象数组,第二个返回一个字典数组。 这里所做的是通过将结果types设置为.DictionaryResultType
来混合解决scheme,但将结果视为托pipe对象的数组。
备注:我build议使用NSFetchedResultsController
在表格视图中显示核心数据读取请求的结果。 FRC高效地pipe理表格视图数据源(可选分组为部分),并在结果集更改时自动更新表格视图。