【问题标题】:Core Data: Showing NSFetchRequestResult Search Results with UITableView核心数据:使用 UITableView 显示 NSFetchRequestResult 搜索结果
【发布时间】:2018-02-25 05:51:44
【问题描述】:

过去几天我一直在玩Core Data。我正在使用NSFetchedResultsController 获取数据。我的实体具有年龄(Int)、名字(字符串)、姓氏(字符串)、uuid(字符串)等属性。我能够在数据库中插入一条新记录。我可以删除记录。我还可以编辑记录。我不能做的是用表格显示搜索结果。

class HomeViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    // MARK: - Instance variables
    private let persistentContainer = NSPersistentContainer(name: "Profiles") // core data model file (.xcdatamodeld)
    var managedObjectContext: NSManagedObjectContext?

    // MARK: - IBOutlets
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var searchButton: UIButton!

    // MARK: - IBActions
    @IBAction func searchTapped(_ sender: UIButton) {
        searchRecords()
    }

    // MARK: - Life cycle
    override func viewDidLoad() {
        super.viewDidLoad()

        // loading persistentContainer //
        persistentContainer.loadPersistentStores { (persistentStoreDescription, error) in
            if let error = error {
                print("Unable to Load Persistent Store")
                print("\(error), \(error.localizedDescription)")
            } else {
                do {
                    try self.fetchedResultsController.performFetch()
                } catch {
                    let fetchError = error as NSError
                    print("Unable to Perform Fetch Request")
                    print("\(fetchError), \(fetchError.localizedDescription)")
                }
            }
        }
    }
    // MARK: - Life cycle

    // MARK: - fetchedResultsController(controller with the entity)
    fileprivate lazy var fetchedResultsController: NSFetchedResultsController<Person> = {
        // Create Fetch Request with Entity
        let fetchRequest: NSFetchRequest<Person> = Person.fetchRequest()

        // Configure Fetch Request
        fetchRequest.sortDescriptors = [NSSortDescriptor(key: "lastName", ascending: true)]

        // Create Fetched Results Controller
        let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.persistentContainer.viewContext, sectionNameKeyPath: nil, cacheName: nil)

        // Configure Fetched Results Controller
        fetchedResultsController.delegate = self
        return fetchedResultsController
    }()
    // MARK: - fetchedResultsController

    // MARK: - TableView
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        guard let people = fetchedResultsController.fetchedObjects else { return 0 }
        return people.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! ProfileTableViewCell
        let person = fetchedResultsController.object(at: indexPath)

        // Configure Cell
        cell.firstLabel.text = person.firstName
        cell.lastLabel.text = person.lastName
        cell.ageLabel.text = String(person.age)
        return cell
    }
    // MARK: - TableView

    // MARK: - Showing search result
    func searchRecords() {
        let context = self.persistentContainer.viewContext
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Person")
        let predicate = NSPredicate(format: "firstName CONTAINS[c] %@", "Sandra")
        fetchRequest.predicate = predicate
        do {
            try fetchedResultsController.performFetch()
            /*
            let result = try context.fetch(fetchRequest)
            if (result.count > 0) {
                print(result.count)
            }
            */
        } catch {
            print("bad")
        }
    }
    // MARK: - Showing search result
}

extension HomeViewController: NSFetchedResultsControllerDelegate {
    func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
        tableView.beginUpdates()
    }

    func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
        tableView.endUpdates()
    }

    func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
        switch (type) {
        case .insert:
            if let indexPath = newIndexPath {
                tableView.insertRows(at: [indexPath], with: .fade)
            }
            break;
        case .delete:
            if let indexPath = indexPath {
                tableView.deleteRows(at: [indexPath], with: .fade)
            }
            break;
        case .update:
            if let indexPath = indexPath {
                tableView.reloadRows(at: [indexPath], with: .automatic)
            }
            break;
        default:
            tableView.reloadData()
        }
    }

    func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) {
    }
}

如果我运行searchRecords()result.count 将正确返回记录数。但桌子保持不变。那么如何在表格中显示我的搜索结果呢?谢谢。

【问题讨论】:

    标签: swift uitableview core-data nsfetchedresultscontroller


    【解决方案1】:

    替换你的tableview数据源
    // MARK: - Table View
    
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return self.fetchedResultsController.sections?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let sectionInfo = self.fetchedResultsController.sections![section]
        return sectionInfo.numberOfObjects
    }
    

    希望对你有帮助

    【讨论】:

    • 有趣...我几乎忽略了它。它确实有效。谢谢。
    【解决方案2】:

    你比我有更多的经验,但我上次使用 CoreData 和 collectionView 我需要强制转换结果如下:

           do {
                return try context.fetch(request) as? [Friend]
            } catch let err {
                print(err)
            }
    

    然后我能够更轻松地将信息拉到表格中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多