【发布时间】:2017-09-23 09:50:20
【问题描述】:
这是我的场景...单击右上角(导航栏)的加号按钮,会出现一个带有文本字段的警报视图,我在文本字段中添加一些数据,然后按确定按钮。这会导致文本字段中的数据显示在 tableview 上,并且它也存储在 core-data 中。
然后,当我单击现在具有来自 alertview 文本字段的数据的那一行时,我会转到另一个用于编辑的视图。这个viewcontroller 有一个文本字段,其值来自上一屏幕的行。现在我单击文本字段并编辑其上的值,然后按右上角的保存。现在,理想情况下,当我按下保存并转到上一个屏幕时,现在应该在 tableview 上看到编辑后的值而不是旧值。
但发生的情况是,当我按下保存并返回上一个屏幕时,我暂时会在 tableviewcontroller 中看到更新后的值。但实际上,该值在 core-data 中添加了两次,当我从这个 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
【问题讨论】: