es.davy.ai

Preguntas y respuestas de programación confiables

¿Tienes una pregunta?

Si tienes alguna pregunta, puedes hacerla a continuación o ingresar lo que estás buscando.

UITableView con Xcode, Problema de obtención de CoreData

He estado trabajando en un proyecto pero tengo problemas para recuperar CoreData en mi TableView. Este es mi código:

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

func loadData() {
let requestData: NSFetchRequest = Person.fetchRequest()
do {
personArr = try context.fetch(requestData)
try context.save()
} catch {
print(“Error al recuperar la solicitud de datos: (error)”)
self.tableView.reloadData()
}
}

// let DVC = segue.destination as! addPersonController
// numberOfRowsInSection … cellForRowAt
// let cell = tableView.dequeueReusableCell(withIdentifier: “personCell”, for: indexPath)
// cell.textLabel?.text = itemArray[indexPath.row].title
// let person = personArr[indexPath.row]

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if tableView.cellForRow(at: indexPath)?.accessoryType == .checkmark {
tableView.cellForRow(at: indexPath)?.accessoryType = .none
personArr[indexPath.row].finish = false
//cell.accessoryType = .checkmark //forRaw
}
tableView.deselectRow(at: indexPath, animated: true) //not selected
savePerson()
// let myPerson = PersonArr[indexPath.row].name
// performSegue(withIdentifier: “personSegue”, sender: myPerson)
}

Aquí hay un ejemplo de una función que apliqué. Mi preocupación está en recuperar los datos en personArr, ya que no se está recuperando como se esperaba. ¿Alguna idea?

Tags:  ,

Answer

  1. Avatar for davy.ai

    Parece que el código está intentando obtener datos de CoreData utilizando NSFetchRequest, pero no hay una comprobación de errores durante la obtención. Además, no hay indicación de dónde se declara o cómo se utiliza personArr en el código.

    Para recuperar datos de CoreData en una TableView, puedes hacer lo siguiente:

    1. En tu ViewController, declara una variable para el fetchedResultsController:
    var fetchedResultsController: NSFetchedResultsController<person>!
    
    1. En tu método viewDidLoad(), inicializa el fetchedResultsController:
    override func viewDidLoad() {
        super.viewDidLoad()
    
        let fetchRequest: NSFetchRequest<person> = Person.fetchRequest()
        let sortDescriptor = NSSortDescriptor(key: "name", ascending: true) // reemplaza "name" con tu propio atributo
        fetchRequest.sortDescriptors = [sortDescriptor]
    
        fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
        fetchedResultsController.delegate = self
    
        do {
            try fetchedResultsController.performFetch()
        } catch {
            print("Error: \(error.localizedDescription)")
        }
    }
    
    1. Implementa los métodos UITableViewDelegate y UITableViewDataSource:
    extension MiViewController: UITableViewDelegate, UITableViewDataSource {
    
        func numberOfSections(in tableView: UITableView) -> Int {
            return fetchedResultsController.sections?.count ?? 0
        }
    
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return fetchedResultsController.sections?[section].numberOfObjects ?? 0
        }
    
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "personCell", for: indexPath)
            let person = fetchedResultsController.object(at: indexPath)
            cell.textLabel?.text = person.name // reemplaza "name" con tu propio atributo
    
            return cell
        }
    
        func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            let person = fetchedResultsController.object(at: indexPath)
            // haz algo con el objeto de la persona seleccionada
        }
    
    }
    
    1. Si deseas actualizar la TableView cuando se agrega o elimina un nuevo objeto a CoreData, implementa los métodos NSFetchedResultsControllerDelegate:
    extension MiViewController: NSFetchedResultsControllerDelegate {
    
        func controllerWillChangeContent(_ controller: NSFetchedResultsController<nsfetchrequestresult>) {
            tableView.beginUpdates()
        }
    
        func controller(_ controller: NSFetchedResultsController<nsfetchrequestresult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
            switch type {
            case .insert:
                tableView.insertRows(at: [newIndexPath!], with: .automatic)
            case .delete:
                tableView.deleteRows(at: [indexPath!], with: .automatic)
            case .update:
                let cell = tableView.cellForRow(at: indexPath!)
                let person = fetchedResultsController.object(at: indexPath!)
                cell?.textLabel?.text = person.name // reemplaza "name" con tu propio atributo
            case .move:
                tableView.moveRow(at: indexPath!, to: newIndexPath!)
            @unknown default:
                fatalError("Caso no manejado")
            }
        }
    
        func controllerDidChangeContent(_ controller: NSFetchedResultsController<nsfetchrequestresult>) {
            tableView.endUpdates()
        }
    
    }
    

    Con esta implementación, la TableView se actualizará automáticamente cuando haya cambios en los objetos de CoreData.

Comments are closed.