如何在没有 NSFetchedResultsControllerDelegate 的情况下获取结果?

How to fetch results without NSFetchedResultsControllerDelegate?

我正在尝试从不是 NSFetchedResultsControllerDelegate 的 class 获取结果,这就是我得到 0 个结果的原因吗?

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
}

这将创建新的专用队列并将代码块带到 运行。这可以与您的容器一起使用,或者您可以使用容器作为参数

func read(_ block: @escaping (NSManagedObjectContext) -> Void) {
    persistentContainer.performBackgroundTask {
        block([=10=])
    }
}

这就是您的使用方式

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