ios - 尝试保存数组时 CoreData 出错。'无法将'String'类型的值转换为预期的参数类型'NSManagedObject''
问题描述
我正在使用 CoreData 将 tableView 保存到设备。我对 CoreData 比较陌生,无法弄清楚这一点。我得到错误:
'Cannot convert value of type 'String' to expected argument type 'NSManagedObject''
在线上:
favourites.append(addNewMemory.text!)
//MARK:- Core Data
func save(name: String) {
guard let appDelegate =
UIApplication.shared.delegate as? AppDelegate else {
return
}
// 1
let managedContext =
appDelegate.persistentContainer.viewContext
// 2
let entity =
NSEntityDescription.entity(forEntityName: "Memory",
in: managedContext)!
let person = NSManagedObject(entity: entity,
insertInto: managedContext)
// 3
person.setValue(name, forKeyPath: "name")
// 4
do {
try managedContext.save()
favourites.append(person)
} catch let error as NSError {
print("Could not save. \(error), \(error.userInfo)")
}
}
var favourites: [NSManagedObject] = []
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return favourites.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: "Cell")
/*cell.imageView?.image = UIImage(named: "applelogo")
cell.imageView?.setRounded()
cell.imageView?.clipsToBounds = true
*/
let favMemory = favourites[indexPath.row]
cell.textLabel?.text = favMemory.value(forKeyPath: "name") as? String
return cell
}
@IBAction func addButtonTapped(_ sender: UIButton) {
insertNewCell()
}
func insertNewCell() {
favourites.append(addNewMemory.text!)
let indexPath = IndexPath(row: favourites.count - 1, section: 0)
tableView.beginUpdates()
tableView.insertRows(at: [indexPath], with: .automatic)
tableView.endUpdates()
addNewMemory.text = ""
view.endEditing(true)
}
我希望应用程序保存字符串,但它不起作用。我怎样才能解决这个问题?
解决方案
您正在混淆text
文本字段和核心数据实体的属性。显然favourites
被声明为[NSManagedObject]
所以你不能附加一个字符串。这就是错误消息告诉您的内容。
您必须在insertNewCell
. 最简单的解决方案是调用save
并返回一个 Bool fromsave
以指示插入成功。
我们鼓励您使用更现代的 API。如果没有Memory
子类创建一个
var favourites = [Memory]()
...
func save(name: String) -> Bool {
let appDelegate = UIApplication.shared.delegate as! AppDelegate // force unwrapping is perfectly fine
// 1
let managedContext = appDelegate.persistentContainer.viewContext
// 2
let person = Memory(context: managedContext)
// 3
person.name = name
// 4
do {
try managedContext.save()
favourites.append(person)
return true
} catch let error as NSError {
print("Could not save. \(error), \(error.userInfo)")
return false
}
}
并更改insertNewCell
为
func insertNewCell() {
guard save(name: addNewMemory.text!) else { return }
let indexPath = IndexPath(row: favourites.count - 1, section: 0)
tableView.insertRows(at: [indexPath], with: .automatic)
addNewMemory.text = ""
view.endEditing(true)
}
beginUpdates/endUpdates
是没有意义的。
推荐阅读
- python - 从元组数组中删除在每个元素的第一个索引位置具有相同值的元素
- flutter - Flutter Downloader:从带有空格的 URL 下载文件
- python - 保护 Flask 应用程序 python 源代码不被复制的最佳方法是什么?
- java - Gmail 无法正确识别我的 HTML Android 意图电子邮件
- reactjs - React 测试库 | 点击时 toHaveStyle 更改,测试失败
- azure-devops - 在 Azure DevOps 中查找作者的评论
- ruby-on-rails - 消息:失败/错误:需要 File.expand_path('../config/environment', __dir__)
- python - Numpy:在没有循环的情况下获取索引中的最小值?
- javascript - 如何访问按钮提交的自声明属性?
- python - dict len 的意外行为