M
M
MarsFM2018-09-04 10:07:31
iOS
MarsFM, 2018-09-04 10:07:31

When to use NSFetchRequest and when to use NSFetchedResultsController?

Plz tell me when is better to use NSFetchRequest and when NSFetchedResultsController?
I'll try to describe what the problem is)
1. NSFetchRequest
When I use NSFetchRequest , I have to create a new array and upload the result of the request there.

var categories: [Category] = [] {
        didSet {
            tableView.reloadData()
        }
    }

I unload in viewDidLoad:
context = CoreDataStack.shared.managedContext
        let request: NSFetchRequest<Category> = Category.fetchRequest()
        
        do {
            if let result = try context?.fetch(request) {
                categories = result // сохраняю в массив
            }
        } catch let error as NSError {
            print("Error fetch request: \(error)")
        }

Next, I use an array to display in cells. Here I do not like that I have to create an array, is it possible to use NSFetchRequest but without creating an array? Or is this the normal approach?
2. NSFetchedResultsController
Here I don't like that it is necessary to use Descriptor without it NSFetchedResultsController won't work. Is there any way to get around this, I don't need sorting.
lazy var fetchResultController: NSFetchedResultsController<Category> = {
        
        let context = CoreDataStack.shared.managedContext
        let request: NSFetchRequest<Category> = Category.fetchRequest()
        
        let sortDescriptor = NSSortDescriptor(key: "name", ascending: true)
        request.sortDescriptors = [sortDescriptor]
        
        let fetchedResultsController = NSFetchedResultsController(fetchRequest: request, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
        
        fetchedResultsController.delegate = self
        
        return fetchedResultsController
    }()

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question