类型“ Item”的值没有成员“ parentCategory”

时间:2018-08-02 15:02:24

标签: ios swift xcode core-data

我有2个实体

enter image description here

我现在正在使用XCode 10,不知道我做错了什么还是XCode错误。

我在这些行中添加了1行

let newItem = Item(context: self.context)
newItem.title = textField.text!
newItem.done = false
newItem.parentCategory = self.selectedCategory <--------- ADD HERE 
self.itemArray.append(newItem)
self.saveItems()

enter image description here

有人暗示我为什么会这样吗?

TodoListVC

//
//  TodoListVC
//  ListHue
//  Copyright © 2018 LR Web Design. All rights reserved.
//

import UIKit
import CoreData

class TodoListVC: UITableViewController {

    var itemArray = [Item]()

    var selectedCategory : Category? {
        didSet {
            loadItems()
        }
    }

    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

    // ---------------------------------------------------------------------------------------------------------
    //MARK - viewDidLoad

    override func viewDidLoad() {
        super.viewDidLoad()

        print(FileManager.default.urls(for: .documentDirectory, in: .userDomainMask))


    }


    // ---------------------------------------------------------------------------------------------------------
    //MARK - Datasource

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return itemArray.count
    }

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

        let cell = tableView.dequeueReusableCell(withIdentifier: "listItemCell", for: indexPath)
        let item = itemArray[indexPath.row]

        cell.textLabel?.text = item.title
        cell.accessoryType = item.done == true ? .checkmark : .none

        return cell

    }


    // ---------------------------------------------------------------------------------------------------------
    //MARK - Delegate

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {


        context.delete(itemArray[indexPath.row])
        itemArray.remove(at: indexPath.row)


        itemArray[indexPath.row].done = !itemArray[indexPath.row].done

        self.saveItems()

        tableView.deselectRow(at: indexPath, animated: true)
    }


    // ---------------------------------------------------------------------------------------------------------
    //MARK - Add new item

    @IBAction func addButtonPressed(_ sender: UIBarButtonItem) {

        var textField = UITextField()
        let alert = UIAlertController(title: "Add New Item", message: "", preferredStyle: .alert)

        //action
        let action = UIAlertAction(title: "Add Item", style: .default) { (action) in


            let newItem = Item(context: self.context)
            newItem.title = textField.text!
            newItem.done = false
            newItem.parentCategory = self.selectedCategory
            self.itemArray.append(newItem)
            self.saveItems()


        }

        alert.addTextField { (alertTextField) in
            alertTextField.placeholder = "Create new item"
            textField = alertTextField
        }

        alert.addAction(action)

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

    }

    // ---------------------------------------------------------------------------------------------------------
    //MARK - Model Manipulation Methods


    func saveItems() {

        do {
            try context.save()
        } catch {
            print("Error saving context, \(error)")
        }

        self.tableView.reloadData()

    }

    func loadItems(with request: NSFetchRequest<Item> = Item.fetchRequest()) {

        let predicate = NSPredicate(format: "parentCategory.name MATCHES %@", selectedCategory?.name!)
        request.predicate = predicate

        do {
            itemArray = try context.fetch(request)
        } catch {
            print("Error fetching data from the context, \(error)")
        }

        self.tableView.reloadData()

    }


}

//MARK: - Search bar methods

extension TodoListVC : UISearchBarDelegate {
    func  searchBarSearchButtonClicked(_ searchBar: UISearchBar) {

        let request : NSFetchRequest<Item> = Item.fetchRequest()

        request.predicate = NSPredicate(format: "title CONTAINS[cd] %@", searchBar.text!)
        request.sortDescriptors = [NSSortDescriptor(key: "title", ascending: true)]

        loadItems(with: request)
    }

    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        if searchBar.text?.count == 0 {

            loadItems()

            DispatchQueue.main.async {
                searchBar.resignFirstResponder()
            }

        }
    }


}

CategoryVC

//
//  CategoryVC.swift
//  ListHue
//  Copyright © 2018 LR Web Design. All rights reserved.
//

import UIKit
import CoreData

class CategoryVC: UITableViewController {

    var categories = [Category]()
    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

    override func viewDidLoad() {
        super.viewDidLoad()

        loadCategories()

    }

    // ---------------------------------------------------------------------------------------------------------
    //MARK - Table View Datasource

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return categories.count
    }

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

        let cell = tableView.dequeueReusableCell(withIdentifier: "CategoryCell", for: indexPath)
        let category = categories[indexPath.row]

        cell.textLabel?.text = category.name


        return cell

    }


    // ---------------------------------------------------------------------------------------------------------
    //MARK - Table View Delegate Methods

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        tableView.deselectRow(at: indexPath, animated: true)
        performSegue(withIdentifier: "goToItems", sender: self)

    }


    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        let destinationVC = segue.destination as! TodoListVC

        //get the category of the selected cell
        if let indexPath = tableView.indexPathForSelectedRow {

            //set the property
            destinationVC.selectedCategory = categories[indexPath.row]

        }

    }


    // ---------------------------------------------------------------------------------------------------------
    //MARK - Data Manipulation Methods

    @IBAction func addButtonPressed(_ sender: UIBarButtonItem) {
        print("click")

        var textField = UITextField()
        let alert = UIAlertController(title: "Add New Category", message: "", preferredStyle: .alert)

        //action
        let action = UIAlertAction(title: "Add Category", style: .default) { (action) in

            let newCategory = Category(context: self.context)
            newCategory.name = textField.text!
            self.categories.append(newCategory)
            self.saveCategories()
        }

        alert.addTextField { (alertTextField) in
            alertTextField.placeholder = "Create new item"
            textField = alertTextField
        }

        alert.addAction(action)

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


    }

    // ---------------------------------------------------------------------------------------------------------
    //MARK - Add New Categories
    func saveCategories() {

        do {
            try context.save()
        } catch {
            print("Error saving context, \(error)")
        }

        self.tableView.reloadData()

    }

    func loadCategories(with request: NSFetchRequest<Category> = Category.fetchRequest()) {

        do {
            categories = try context.fetch(request)
        } catch {
            print("Error fetching data from the context, \(error)")
        }

        self.tableView.reloadData()

    }

}

1 个答案:

答案 0 :(得分:1)

由于@Larme,我使图表向后了,@ Ladislav帮助我知道了这一点。

enter image description here