我有一个度假应用程序,在初始视图控制器中,我可以从API获取城市的天气,当我选择一行时,它会跳转到另一个视图控制器,在那里我可以向行程添加待办事项列表。我让一切工作,我只是不知道如何处理从行程中删除行。当我试图删除一行时,它说:
无效的更新:无效的行数在第0节。
下面是我的代码:
import UIKit
import CoreData
class ToDoViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var itineraryTextField: UITextField!
@IBOutlet weak var editCityName: UITextField!
@IBOutlet weak var editTripName: UITextField!
var myFetchRCTripName: Trip?
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func editTrip(_ sender: Any) {
if !(editCityName.text!.isEmpty) && !(editTripName.text!.isEmpty){
myFetchRCTripName!.cityName = editCityName.text
myFetchRCTripName!.tripName = editTripName.text
CoreDataStack.shared.saveContext()
} else{
print ("error")
}
}
@IBAction func addToDo() {
//add to itinerary
let itin = Itinerary(context: CoreDataStack.shared.persistentContainer.viewContext)
itin.toDo = itineraryTextField.text
//set owner
itin.owner = myFetchRCTripName
myFetchRCTripName!.addToItineraries(itin)
tableView.reloadData()
CoreDataStack.shared.saveContext()
}
}
extension ToDoViewController: UITableViewDelegate, UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return myFetchRCTripName?.itineraries?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath)
if let itin = myFetchRCTripName!.itineraries {
let itemsOnListArray = itin.allObjects
let i = itemsOnListArray[indexPath.row] as! Itinerary
cell.textLabel?.text = i.toDo
}
return cell
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete{
var itemsOnListArray = myFetchRCTripName!.itineraries?.allObjects
itemsOnListArray?.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .automatic)
}
}
}
我解决了这个问题:
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete{
let itemsOnListArray = myFetchRCTripName!.itineraries?.allObjects
let obj = itemsOnListArray?[indexPath.row] as! Itinerary
myFetchRCTripName!.removeFromItineraries(obj)
tableView.deleteRows(at: [indexPath], with: .automatic)
CoreDataStack.shared.saveContext()
}
}