Fetching Core Data in the background

后端 未结 1 657
误落风尘
误落风尘 2021-02-03 16:10

I have a Navigation View with a Table View, when a row is clicked, the row indexPath is passed to the next view.

in the Details view viewDidLoad, i am fetching data from

相关标签:
1条回答
  • 2021-02-03 16:24

    Mixing multithreading and Core Data is not a simple task. The "Multi-Threading with Core Data" section of the Core Data Programming Guide describes how to interact with Core Data on multiple threads, including all the things that you need to be careful of.

    Basically, you will need to create a separate managed object context for each thread. These contexts can share access to one managed object model and persistent store. For your case, they suggest the following:

    You use two managed object contexts associated with a single persistent store coordinator. You fetch in one managed object context on a background thread, and pass the object IDs of the fetched objects to another thread. In the second thread (typically the application's main thread, so that you can then display the results), you use the second context to fault in objects with those object IDs (you use objectWithID: to instantiate the object).

    It sounds like the BackgroundFetching sample application shows how to do this, but I don't have it on my system.

    However, before you get too far into multithreading your fetch request, I'd take a hard look into why it's taking so long to load. I'd first recommend using -setFetchBatchSize: on your NSFetchRequest to limit the number of objects loaded into memory via your fetch (which will save you a lot of memory, too). Next, I'd use -setPropertiesToFetch: to limit the properties fetched to only those you'll be using immediately.

    0 讨论(0)
提交回复
热议问题