Search code examples
iosswiftcore-datansfetchedresultscontroller

How to fetch results without NSFetchedResultsControllerDelegate?


I am trying to fetch results from a class that is not a NSFetchedResultsControllerDelegate is that why I am getting 0 results?

public static func getTopics() -> Array<ipTopic> {
    if (topics == nil) {
        var fetchedResultsController: NSFetchedResultsController<ipTopic>!
        let pc = CoreDataHub.getPersistentContainer()
        let blogIdeasFetchRequest = NSFetchRequest<ipTopic>(entityName: "ipTopic")
        let primarySortDescriptor = NSSortDescriptor(key: "ipTopicsClip", ascending: true)
        blogIdeasFetchRequest.sortDescriptors = [primarySortDescriptor]
        
        fetchedResultsController = NSFetchedResultsController<ipTopic>(
            fetchRequest: blogIdeasFetchRequest,
            managedObjectContext: pc.viewContext,
            sectionNameKeyPath: nil,
            cacheName: nil)
        do {
            try fetchedResultsController.performFetch()
        } catch {
            print("An error occurred")
            
        }
        print(fetchedResultsController.fetchedObjects?.count)
        for topic in fetchedResultsController.fetchedObjects! {
            topics.append(topic)
        }
    }
    return topics
}

Solution

  • This will creates new private queue and takes a block of code to run. This can live with your container or you can use container as argument

    func read(_ block: @escaping (NSManagedObjectContext) -> Void) {
        persistentContainer.performBackgroundTask {
            block($0)
        }
    }
    

    This is how you would use it

    func fetchEvents() {
        read { context in
            let request: NSFetchRequest<Event> = Event.fetchRequest()
            let events = try? context.fetch(request)
            print(events)
        }
    }