【发布时间】:2018-11-29 00:41:55
【问题描述】:
我在上一个TableView中选择Class单元格后尝试通过单击按钮添加学生姓名,我面临的问题是,例如我有三个班级,班级A,B,C。然后我选择A 类创建学生 X,但是当我回到 B 类或 C 类时,我也在这些类中看到学生 X。我意识到我对所有类都使用了相同的数据,但我无法解决这个问题。
import UIKit
import CoreData
class StudentListViewController: UIViewController, UITableViewDataSource,UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
var studentList = [StudentData]()
var student: StudentData?
override func viewDidLoad() {
super.viewDidLoad()
let fetchRequest: NSFetchRequest<StudentData> = StudentData.fetchRequest()
do {
let studentList = try PersistenceService.context.fetch(fetchRequest)
self.studentList = studentList
self.tableView.reloadData()
} catch {}
}
@IBAction func addStudentTapped(_ sender: UIBarButtonItem) {
let alert = UIAlertController(title: "Add Student", message: nil, preferredStyle: .alert)
alert.addTextField { (studentListTF) in
studentListTF.placeholder = "Enter name"
}
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
let action = UIAlertAction(title: "Add", style: .default) { (_) in
guard let student = alert.textFields?.first?.text else { return }
print(student)
let person = StudentData(context: PersistenceService.context)
person.student_name = student
PersistenceService.saveContext()
self.studentList.append(person)
self.tableView.reloadData()
}
alert.addAction(action)
present(alert,animated: true)
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return studentList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let stuCell = tableView.dequeueReusableCell(withIdentifier: "studentCell", for: indexPath)
stuCell.textLabel?.text = studentList[indexPath.row].student_name
return stuCell
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
guard editingStyle == .delete else {return}
let person = studentList[indexPath.row]
studentList.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .fade)
PersistenceService.context.delete(person)
PersistenceService.saveContext()
let fetchRequest: NSFetchRequest<StudentData> = StudentData.fetchRequest()
do {
let studentList = try PersistenceService.context.fetch(fetchRequest)
self.studentList = studentList
} catch {}
self.tableView.reloadData()
print("Delete \(person)")
}
}
【问题讨论】:
标签: swift uitableview uiviewcontroller