我正在尝试解决错误,正在使用CoreData持久性和SearchBar过滤,但是我的代码始终保留最后一个项目,始终显示最后添加的项目,其中包含NSPredicate
,
任何反馈。
谢谢
代码如下:
import UIKit
import CoreData
class ToDoeyViewController: UITableViewController {
@IBOutlet weak var searchBar: UISearchBar!
var itemArray = [Item]()
var selectedCategory: Category? {
didSet {
loadItems()
}
}
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
override func viewDidLoad() {
super.viewDidLoad()
print(FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first?.appendingPathComponent("Items.plist"))
searchBar.delegate = self
}
//MARK - TableView DataSocurce Methods
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return itemArray.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let item = itemArray[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "ToDoCell", for: indexPath)
cell.textLabel!.text = item.title
// Ternary operator ==>
// value = condition1 ? valueIfTrue:ValueIfFalse
cell.accessoryType = item.done == true ? .checkmark:.none
return cell
}
//MARK: - TableView Delegate Methods
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// print(itemArray[indexPath.row])
itemArray[indexPath.row].done = !itemArray[indexPath.row].done
saveItems()
tableView.deselectRow(at: indexPath, animated: true)
}
//MARK: - Add new items
@IBAction func addButtonPressed(_ sender: UIBarButtonItem) {
var textField = UITextField()
let alert = UIAlertController(title: "Add new item", message: "", preferredStyle: .alert)
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 a new Item"
textField = alertTextField
}
alert.addAction(action)
present(alert, animated: true, completion: nil)
}
// MARK: - Methods
func saveItems() {
do {
try context.save()
} catch {
print("Error saving context \(error)")
}
tableView.reloadData()
}
func loadItems(with request: NSFetchRequest<Item> = Item.fetchRequest(), predicate: NSPredicate? = nil) {
let categoryPredicate = NSPredicate(format: "parentCategory.name MATCHES %@", selectedCategory!.name!)
if let additionalPredicate = predicate {
request.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [categoryPredicate, additionalPredicate])
} else {
request.predicate = categoryPredicate
}
// let compoundPredicate = NSCompoundPredicate(andPredicateWithSubpredicates: [categoryPredicate, predicate])
//
// request.predicate = compoundPredicate
do {
itemArray = try context.fetch(request)
} catch {
print("Error fetching context \(error)")
}
tableView.reloadData()
}
}
//MARK: - Search Bar Methods
extension ToDoeyViewController: UISearchBarDelegate {
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
let request: NSFetchRequest<Item> = Item.fetchRequest()
let predicate = NSPredicate(format: "title CONTAINS[cd] %@", searchBar.text!)
request.sortDescriptors = [NSSortDescriptor(key: "title", ascending: true)]
loadItems(with: request, predicate: predicate )
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchBar.text?.count == 0 {
loadItems()
DispatchQueue.main.async {
searchBar.resignFirstResponder()
}
}
}
}