在 viewContext 上使用 perform 方法和不使用 perform 方法有什么区别? - 核心数据

What is difference between using perform method and not using perform method on viewContext ? - CoreData

背景

我是 CoreData 的初学者。直到现在,每当我需要使用 CoreData 时,我都会在任何地方使用 perform 方法——比如获取、保存、更新…… 因此,我还使用 completion closure block 来传递从获取中产生的数据。
当然,我总是使用 viewContext 因为我制作的应用程序不需要太多数据。和我想的一样,App运行良好。

但是,在我更多地考虑 CoreData 之后,我意识到 " 如果我​​使用 viewContext,我不必使用 perform 方法,而且我不必使用 completion closure block.".

因为 viewContext 是 CoreData 的主队列。

问题

我的问题是“如果我使用viewContext并且我不需要在后台队列中执行任务,我可以不使用perform方法吗?”

如果你能回答我,我将不胜感激。

代码

根据我到现在为止使用的代码。

    func fetchTags(_ completion: @escaping (([Tag]?) -> Void )) {
        context.perform {
            let request: NSFetchRequest<Tag> = Tag.fetchRequest()
            guard let list = try? self.context.fetch(request) else {
                return completion(nil)
            }
            completion(list)
        }
    }

代码下我觉得比较好

    func fetchTags() -> [Tag]? {
        let request: NSFetchRequest<Tag> = Tag.fetchRequest()
        guard let list = try? self.context.fetch(request) else {
            return nil
        }
        return list
    }

如果您正在使用 viewContext并且您的代码在主队列 运行 上 ,则 performperformBlock 是不必要的。如果总能保证代码运行在主队列上,就可以简化。如果有可能 运行 它出现在其他队列中,您需要采取预防措施以避免崩溃。