无法使用Core Data将项目添加到列表中

时间:2016-10-03 13:23:07

标签: swift core-data swift3

当我按下添加时,没有项目被添加到列表中。我的代码出了什么问题? 我正在尝试使用Core Data制作持久性的购物清单。 请帮我。 在Core Data部分或使用alertController是错误的吗?

import UIKit
import CoreData

class GroceryTableTableViewController: UITableViewController {

var groceries = [NSManagedObject]()

override func viewDidLoad() {

    super.viewDidLoad()
    self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")

    }

override func viewWillAppear(_ animated: Bool) {
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let managedContext = appDelegate.persistentContainer.viewContext

    super.viewWillAppear(animated)

    loadData()
}

func loadData(){
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let managedContext = appDelegate.persistentContainer.viewContext

    let request:NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: "Groceries")

    do {
        let results = try managedContext.fetch(request)
        groceries = results as! [NSManagedObject]

    }
    catch {
        //print(<#T##items: Any...##Any#>)("Error in retrieving Grocery items")

        let fetchError = error as NSError
        print(fetchError)
    }

}


@IBAction func addAction(_ sender: UIBarButtonItem) {

    let alertController = UIAlertController(title: "Grocery List", message: "Add Item", preferredStyle: UIAlertControllerStyle.alert)

    alertController.addTextField { (textField : UITextField!) -> Void in

    }

    let addAction = UIAlertAction(title: "Add", style:UIAlertActionStyle.default) { (action: UIAlertAction) -> Void in


        func saveItem(itemToSave : String) {
            let appDelegate = UIApplication.shared.delegate as! AppDelegate
            let managedContext = appDelegate.persistentContainer.viewContext


            let entityDescription = NSEntityDescription.entity(forEntityName: "Groceries", in: managedContext)
            let item = NSManagedObject(entity: entityDescription!, insertInto: managedContext)

            item.setValue(itemToSave, forKey: "item")

         do {
                try managedContext.save()

                self.groceries.append(item)
            }
            catch {
                print("Error in storing to Core Data")
            }
        }

        self.loadData()
    }

    let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.default) { (action: UIAlertAction) -> Void in
    }

    alertController.addAction(addAction)

    alertController.addAction(cancelAction)

    present(alertController, animated: true, completion: nil)

}

// MARK: - Table view data source

override func numberOfSections(in tableView: UITableView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    return groceries.count
}


override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    let item = groceries[indexPath.row]
    cell.textLabel?.text = item.value(forKey: "item") as! String

    return cell
}


/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    // Return false if you do not want the specified item to be editable.
    return true
}
*/

/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {
        // Delete the row from the data source
        tableView.deleteRows(at: [indexPath], with: .fade)
    } else if editingStyle == .insert {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }    
}
*/

/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {

}
*/

/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
    // Return false if you do not want the item to be re-orderable.
    return true
}
*/

/*
// MARK: - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.
}
*/

}

0 个答案:

没有答案