我正在使用 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
属性和 Core Data 实体。显然 favorites
被声明为 [NSManagedObject]
所以你不能追加一个字符串。这就是错误消息告诉您的内容。
您必须在 insertNewCell
中插入一条新记录。最简单的解决方案是调用 save
并从 save
返回一个 bool 值以指示插入成功。
我们鼓励您使用更现代的 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
毫无意义。
关于ios - 尝试保存数组时 CoreData 出错。 'Cannot convert value of type ' String' 到预期参数类型 'NSManagedObject' ',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57887414/