xcode 使用 NSFetchRequest 从 CoreData 填充 TableView

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42676625/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 09:50:03  来源:igfitidea点击:

Populate TableView from CoreData with NSFetchRequest

swiftxcodeuitableviewcore-datansfetchrequest

提问by Matt

I need to populate my table view with the data from my core data. I can display my rows but, I can't populate my tableview! I use Swift 3 and Xcode 8. This is my code, in this controller I have to display the list.

我需要用我的核心数据中的数据填充我的表视图。我可以显示我的行,但是,我无法填充我的 tableview!我使用 Swift 3 和 Xcode 8。这是我的代码,在这个控制器中我必须显示列表。

class iTableViewController: UITableViewController, NSFetchedResultsControllerDelegate{
@IBOutlet var iTableView: UITableView!


override func viewDidLoad(){
    super.viewDidLoad()

    iTableView.dataSource = self
    iTableView.delegate = self

    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let managerContext = appDelegate.persistentContainer.viewContext
    let interventsFetch = NSFetchRequest<NSFetchRequestResult>(entityName: "Intervento")

    do{
        //results
        let fetchedIntervents = try managerContext.fetch(interventsFetch) as! [Intervento]

        for interv in fetchedIntervents{
            print(interv.stampRow())
        }

        NSLog(String(fetchedIntervents.count))
    }catch{
        fatalError("Failed to fetch employees: \(error)")
    }
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

//number of sections
override func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

//numer of rows
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 1
}

//cell
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.subtitle, reuseIdentifier: "cell")

    cell.accessoryType = UITableViewCellAccessoryType.disclosureIndicator

    //print the example cell
    cell.textLabel?.text = "title"
    cell.detailTextLabel?.text = "subtitle"
    return cell
}

//swipe and delete
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath){
    if(editingStyle == UITableViewCellEditingStyle.delete){
        //TODO
    }
}

// click cell
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
    performSegue(withIdentifier: "segueDetail", sender: self)
}


override func viewDidAppear(_ animated: Bool){
    //iTableView.reloadData()
}

override func viewWillDisappear(_ animated: Bool) {
    //iTableView.reloadData()
    //fetchData()
}
}

this is my class

这是我的班级

extension Intervento {

@nonobjc public class func fetchRequest() -> NSFetchRequest<Intervento> {
    return NSFetchRequest<Intervento>(entityName: "Intervento");
}

@NSManaged public var cliente: Int32
@NSManaged public var dataFine: String?
@NSManaged public var dataInizio: String?
@NSManaged public var descrizione: String?
@NSManaged public var foto: String?
@NSManaged public var id: Int32
@NSManaged public var stato: String?
@NSManaged public var tecnico: String?

func stampRow()->String{
    let v1 = String(id) + " " + String(cliente) + " "
    let v2 = dataInizio! + " " + dataFine! + " "
    let v3 = stato! + " " + tecnico! + " " + descrizione!
    return v1 + v2 + v3
}
}

and this is the my code for save the data (it works)

这是我保存数据的代码(它有效)

 @IBAction func addButton(_ sender: Any){
    //genero la data
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "dd-MM-yyyy HH:mm"
    let strDate = dateFormatter.string(from: myDatePicker.date)

    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let managerContext = appDelegate.persistentContainer.viewContext
    let newInt = NSEntityDescription.insertNewObject(forEntityName: "Intervento", into: managerContext)

    newInt.setValue(1, forKey: "id")
    newInt.setValue(strDate, forKey: "dataInizio")
    newInt.setValue("", forKey: "dataFine")
    newInt.setValue(2, forKey: "cliente")
    newInt.setValue("Matt", forKey: "tecnico")
    newInt.setValue(stato[1], forKey: "stato")
    newInt.setValue("", forKey: "descrizione")
    newInt.setValue("", forKey: "foto")

    do{
        try managerContext.save()
        print("saved")
    }catch let error as NSError{
        //errore salvataggio
        print("Could not fetch \(error), \(error.userInfo)")
    }
}

回答by Mariusz Wiazowski

First of all, your class should implement this protocols:

首先,你的类应该实现这个协议:

UIViewController, UITableViewDataSource, UITableViewDelegate, NSFetchedResultsControllerDelegate

You can load data from a persistent storage with this code:

您可以使用以下代码从持久存储加载数据:

//load data

//persistant container
let persistentContainer = NSPersistentContainer.init(name: "Model")

//
lazy var fetchedResultsController: NSFetchedResultsController<Intervento> = {
    // Create Fetch Request
    let fetchRequest: NSFetchRequest<Intervento> = Intervento.fetchRequest()

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

    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let managerContext = appDelegate.persistentContainer.viewContext

    // Create Fetched Results Controller
    let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: managerContext, sectionNameKeyPath: nil, cacheName: nil)

    // Configure Fetched Results Controller
    fetchedResultsController.delegate = self

    return fetchedResultsController
}()

//carica
func load(){
    //persistant container
    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)")
            }

        }
    }
}

override func viewDidLoad(){
    super.viewDidLoad()

    iTableView.delegate = self
    iTableView.dataSource = self

    // trigger load
    load()
}

Your data will be fetched and will show up because you have delegated iTableViewController by this line of code:

您的数据将被获取并显示出来,因为您已通过以下代码行委托了 iTableViewController:

// Configure Fetched Results Controller
fetchedResultsController.delegate = self

In order to make this work, your ViewController must conform to NSFetchedResultsControllerDelegate protocol, here you can find a possibile implementation:

为了让这个工作,你的 ViewController 必须符合 NSFetchedResultsControllerDelegate 协议,在这里你可以找到一个可能的实现:

extension iTableViewController: NSFetchedResultsControllerDelegate {

func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
    iTableView.beginUpdates()
}

func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
    iTableView.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 {
            iTableView.insertRows(at: [indexPath], with: .fade)
        }
        break;
    case .delete:
        if let indexPath = indexPath {
            iTableView.deleteRows(at: [indexPath], with: .fade)
        }
        break;
    case .update:
        if let indexPath = indexPath, let cell = iTableView.cellForRow(at: indexPath) {
            configureCell(cell, at: indexPath)
        }
        break;
    case .move:
        if let indexPath = indexPath {
            iTableView.deleteRows(at: [indexPath], with: .fade)
        }

        if let newIndexPath = newIndexPath {
            iTableView.insertRows(at: [newIndexPath], with: .fade)
        }
        break;
    }
}
}

In conclusion, this is the full implementation of your iTableViewController(I have included also the necessary code for deleting an row):

总之,这是您的 iTableViewController完整实现(我还包含了删除行的必要代码):

class iTableViewController: UIViewController, UITableViewDataSource, UITableViewDelegate{
@IBOutlet var iTableView: UITableView!

//load data

//persistant container
let persistentContainer = NSPersistentContainer.init(name: "Model")

//
lazy var fetchedResultsController: NSFetchedResultsController<Intervento> = {
    // Create Fetch Request
    let fetchRequest: NSFetchRequest<Intervento> = Intervento.fetchRequest()

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

    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let managerContext = appDelegate.persistentContainer.viewContext

    // Create Fetched Results Controller
    let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: managerContext, sectionNameKeyPath: nil, cacheName: nil)

    // Configure Fetched Results Controller
    fetchedResultsController.delegate = self

    return fetchedResultsController
}()

//carica
func load(){
    //persistant container
    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)")
            }

        }
    }
}


override func viewDidLoad(){
    super.viewDidLoad()

    iTableView.delegate = self
    iTableView.dataSource = self

    // trigger load
    load()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

//numero di sezioni
func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

//numero di righe
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    guard let quotes = fetchedResultsController.fetchedObjects else { return 0 }
    return quotes.count
}

//gestisco la cella
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    //genero la cella
    let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.subtitle, reuseIdentifier: "cell")

    configureCell(cell, at:indexPath)
    return cell
}

//swipe and delete
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath){
    if(editingStyle == .delete){

        // Fetch Quote
        let quote = fetchedResultsController.object(at: indexPath)

        // Delete Quote
        quote.managedObjectContext?.delete(quote)
    }
}

// click cell
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
    performSegue(withIdentifier: "segueDetail", sender: self)
}


func configureCell(_ cell: UITableViewCell, at indexPath: IndexPath) {

    //get intervento
    let intervento = fetchedResultsController.object(at: indexPath)

    //fill the cell
    cell.textLabel?.text = intervento.dataInizio
    cell.detailTextLabel?.text = "SOME_THING"
}

//quando appare aggiorno la table view
override func viewDidAppear(_ animated: Bool){
    self.iTableView.reloadData()
}
}

extension iTableViewController: NSFetchedResultsControllerDelegate {

func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
    iTableView.beginUpdates()
}

func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
    iTableView.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 {
            iTableView.insertRows(at: [indexPath], with: .fade)
        }
        break;
    case .delete:
        if let indexPath = indexPath {
            iTableView.deleteRows(at: [indexPath], with: .fade)
        }
        break;
    case .update:
        if let indexPath = indexPath, let cell = iTableView.cellForRow(at: indexPath) {
            configureCell(cell, at: indexPath)
        }
        break;
    case .move:
        if let indexPath = indexPath {
            iTableView.deleteRows(at: [indexPath], with: .fade)
        }

        if let newIndexPath = newIndexPath {
            iTableView.insertRows(at: [newIndexPath], with: .fade)
        }
        break;
    }
}
}

Don't forget to use always the same context when you make operations with your data (for example when you add new data).

在对数据进行操作时(例如添加新数据时),不要忘记始终使用相同的上下文。

let appDelegate = UIApplication.shared.delegate as! AppDelegate
let managerContext = appDelegate.persistentContainer.viewContext

For a full example you should look here: https://github.com/bartjacobs/ExploringTheFetchedResultsControllerDelegateProtocol

有关完整示例,您应该在这里查看:https: //github.com/bartjacobs/ExploringTheFetchedResultsControllerDelegateProtocol

回答by Gurjinder Singh

Swift 3.3

斯威夫特 3.3

  lazy var fetchedResultsController: NSFetchedResultsController<SavedContact> = {
                    let fetchReqest: NSFetchRequest<SavedContact> = SavedContact.fetchRequest()
                    fetchReqest.sortDescriptors = [NSSortDescriptor(key: "id", ascending: true)]
                    let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchReqest, managedObjectContext: Database.shared.mainManagedObjectContext, sectionNameKeyPath: nil, cacheName: nil)
                    fetchedResultsController.delegate = self
                    return fetchedResultsController
                  }()

       override func viewDidLoad() {
           super.viewDidLoad()
           self.performFetch()
         }
       func performFetch() {
         do {
                 try self.fetchedResultsController.performFetch()
            } catch {
                 Debug.Log(message: "Error in fetching Contact \(error)")
            }
    }
    //MARK: - NSFetchResultcontrollerDelegate
    extension YourViewC: NSFetchedResultsControllerDelegate {

          func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
            self.tableView.reloadData()
          }
        }
// Database Class    
    private let _singletonInstance: Database = Database()

    class Database: NSObject {
         class var shared: Database {
                  return _singletonInstance
                 }

        override init() {
               super.init()
         }
        // Main Managed Object Context
        lazy var mainManagedObjectContext: NSManagedObjectContext = {

               let coordinator = self.persistentStoreCoordinator
               var mainManagedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
                mainManagedObjectContext.persistentStoreCoordinator = coordinator
                 return mainManagedObjectContext
           }()
    // Persistent Store Coordinator
         lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {

           let mOptions = [NSMigratePersistentStoresAutomaticallyOption: true,
                                    NSInferMappingModelAutomaticallyOption: true]
           let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
           let url = self.applicationDocumentsDirectory.appendingPathComponent("AppName.sqlite")
            var failureReason = "There was an error creating or loading the application's saved data."
            do {
                        try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: mOptions)
                    } catch {
                        // Report any error we got.
                        var dict = [String: AnyObject]()
                        dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject?
                        dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject?

                        dict[NSUnderlyingErrorKey] = error as NSError
                        let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
                        abort()
                    }
                    return coordinator
                }()
    // DB Directory and Path
          lazy var applicationDocumentsDirectory: URL = {

                    let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
                    let documentDirectoryURL = urls[urls.count - 1] as URL
                    let dbDirectoryURL = documentDirectoryURL.appendingPathComponent("DB")

                    if FileManager.default.fileExists(atPath: dbDirectoryURL.path) == false{
                        do{
                            try FileManager.default.createDirectory(at: dbDirectoryURL, withIntermediateDirectories: false, attributes: nil)
                        }catch{
                        }
                    }
                    return dbDirectoryURL
                }()
    }