[英]Issue with updating entries in tableview (after editing)and showing in Tableview
这是我的情况...单击导航栏右上角的加号按钮时,将出现一个带有文本字段的Alertview,然后在文本字段中添加一些数据,然后按OK按钮。 这导致文本字段中的数据显示在表格视图中,并且也存储在核心数据中。
然后,当我单击现在具有来自alertview文本字段的数据的行时,我转到另一个要编辑的视图。 该viewcontroller
具有一个文本字段,该字段具有上一屏幕行中的值。 现在,我单击文本字段并编辑它的值,然后按右上角的保存。 现在,理想情况下,当我按保存并转到上一个屏幕时,现在应该在表格视图中看到已编辑的值,而不是原来的值。
但是发生的是,当我按保存并返回上一屏幕时,我暂时在tableviewcontroller
看到更新的值。 但实际上,该值在核心数据添加两次,当我回去从这个tableview
一些其他视图,并返回到它,然后我看到不仅是编辑也是新编辑的值是之前存在的价值加了两次! 我无法理解这种行为。
在编辑屏幕中单击“保存”按钮时,这就是我正在做的...
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "save" {
editedModel = editTextField.text
}
}
回到表视图屏幕,这就是我正在做的...(在tableviewcontroller
屏幕中)
@IBAction func saveToMainEditViewController (segue:UIStoryboardSegue) {
let detailViewController = segue.source as! EditCategoriesTableViewController
let index = detailViewController.index
let modelString = detailViewController.editedModel //Edited model has the edited string
let myCategory1 = Category(context: self.context)
myCategory1.categoryName = modelString
mangObjArr[index!] = myCategory1
//Saving to CoreData
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
return
}
let managedContext = appDelegate.persistentContainer.viewContext
let entity = NSEntityDescription.entity(forEntityName: "Category", in: managedContext)
let category = NSManagedObject(entity: entity!, insertInto: managedContext)
category.setValue(myCategory1.categoryName, forKeyPath: "categoryName")
category.setValue(myCategory1.categoryId, forKey: "categoryId")
do {
try managedContext.save()
} catch let error as NSError {
print("Could not save. \(error), \(error.userInfo)")
}
categoryTableView.reloadData()
}
在cellForRowAtIndexPath中,这就是我正在做的...
let cell = tableView.dequeueReusableCell(withIdentifier: "categoryCell", for: indexPath)
let person = mangObjArr[indexPath.row]
cell.textLabel?.text = person.categoryName
return cell
您要插入新记录,而不是更新前一个记录
在对Category实体进行任何插入之前,编写一段代码,以当前名称获取记录,然后用编辑后的字符串替换其当前名称,然后保存。
此代码使用旧名称获取记录,并用新名称替换其名称
let fetchRequest : NSFetchRequest<Category> = Category.fetchRequest()
fetchRequest.predicate = NSPredicate(format: "(categoryName == %@)", argumentArray: [*Your current categoryName*])
do {
let result = try managedContext.fetch(fetchRequest)
if let toBeUpdatedRecord = result.first
{
toBeUpdatedRecord.categoryName = newName
//here you should save
}
} catch{}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.