1
votes

I've really seen all answers about the title, but all of them were written in Objetive-C, any idea of that in Swift??

This is my code:

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    let respuesta = self.funcCoreData.obtenerResultados(entidad: "Clientes", orden: "nombre_comercial", ascendente: true)
    self.objeto = respuesta[0] as! NSFetchRequest<NSManagedObject>
    self.resultados = respuesta[1] as! NSFetchedResultsController<NSManagedObject>
    do {
        try self.resultados.performFetch()
        if self.funcCoreData.objetoLleno(objeto: self.objeto) {
            self.pintarSecciones()
        }
    } catch {
        print("???????????????? \(error)")
    }
}

File funcCoreData.swift

func obtenerResultados(entidad: String, orden: String, ascendente: Bool) -> [AnyObject] {
    let appDelegate = UIApplication.shared.delegate as? AppDelegate
    let context = appDelegate?.persistentContainer.viewContext
    let objeto = recorrerObjeto(entidad: entidad, orden: orden, ascendente: ascendente)
    let recorrerResultados = NSFetchedResultsController<NSManagedObject>(fetchRequest: objeto, managedObjectContext: context!, sectionNameKeyPath: "seccionLetra", cacheName: nil)

    var array = [AnyObject]()
    array.append(objeto)
    array.append(recorrerResultados)

    return array
}

func recorrerObjeto(entidad: String, orden: String, ascendente: Bool) -> NSFetchRequest<NSManagedObject> {
    let objeto = NSFetchRequest<NSManagedObject>(entityName: entidad)
    let ordenacion = NSSortDescriptor(key: orden, ascending: ascendente, selector: #selector(NSString.caseInsensitiveCompare))
    objeto.sortDescriptors = [ordenacion]
    return objeto
}

I have to put a thread, like DispatchQueue.global(qos: .background).async but, I don't know where!

1
No, it doesn't... >.<' - bey23
Hey, I'm working in a company, so I shouldn't share all my code, but I will edit tomorrow this post and you can see which is my problem maybe. Thank you! - bey23
What? But you are going to help or not? @SwiftDeveloper xd - bey23

1 Answers

0
votes

You don't need an array that contains the fetchRequest and the fetchedResultsController. This makes the code needlessly complex. You can get the objects that are fetched from the fetchedResultsController fetchedObjects property, and if you need the fetchRequest you can get it from the fetchedResultsController.fetchRequest.

I don't know what self.funcCoreData.objetoLleno or self.pintarSecciones is doing but I suspect that it is unnecessary and leading to the crash. If you have code that is enumerating through the fetchedResultsController.fetchedObjects then you have to copy the objects before doing that. fetchedObjects can change while you are looping though it and lead to a crash.