【问题标题】:Fetching multiple entities from CoreData从 CoreData 获取多个实体
【发布时间】:2016-03-28 05:38:05
【问题描述】:

我正在尝试从 CoreData 获取多个实体。我已经在 viewDidAppear 函数中尝试过了。但是,由于数据量很大,从服务器中的远程 JSON 保存,获取它似乎需要时间。我什至关注了这个tutorial。 但是获取大量数据似乎有点慢。有没有更好的办法。

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    let context: NSManagedObjectContext? = (UIApplication.sharedApplication().delegate as? AppDelegate)?.managedObjectContext!

    let TPTodayFetchRequest = NSFetchRequest(entityName: Constants.CoreDataEntities.TPTodayCoreDataEntity)

    let mahinaSort = NSSortDescriptor(key: "month_np_id", ascending: true)
    TPTodayFetchRequest.sortDescriptors = [mahinaSort]
    let error: NSError? = nil

    do {

        let patroDailyResults = try context!.executeFetchRequest(TPTodayFetchRequest) as? [TPToday]


        if let results = patroDailyResults
        {
            patroDaily = results
        }
        else
        {
            print("Couldn't fetch \(error), \(error!.userInfo)")
        }
    }
    catch {
        print("error")
    }


    self.refreshUI()
}

现在我的问题是,从 CoreData 获取实体的最佳方法是什么,以便获取过程顺利进行并且不影响应用程序性能。这段代码 sn-p 非常适合获取,但我想让它更快。

【问题讨论】:

    标签: ios swift nsfetchrequest


    【解决方案1】:

    我怀疑你能不能让它更快,但是这样长时间运行的操作不应该在主线程上运行。

    相反,您应该遵循此模式在后台线程上进行抓取,并在完成后更新受影响的 UI:

    let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
    dispatch_async(dispatch_get_global_queue(priority, 0)) {
        // fetch data
        dispatch_async(dispatch_get_main_queue()) {
            // update some UI
        }
    }
    

    【讨论】:

    • 我最近有了在后台运行获取方法并在主线程中刷新 UI 的想法。我在尝试在 viewWillAppear() 方法中运行提取时也犯了一个错误,就我的情况而言,它应该在 viewDidLoad()_ 方法上运行。无论如何,谢谢你的回答! @Wujo
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-29
    相关资源
    最近更新 更多