'Use .fetchBatchSize with @FetchRequest in SwifUI
I've been trying to understand and figure it out for a few days now, but still couldn't come up with solution.
For example, there is a core data entity with 1 mil rows, and I want to display all the record in a view with a "load as you scroll" in order increase the perfomance, as loading 1 mil rows on load would be slow and wasteful.
From the documentaion basically .fetchBatchSize will load 'batches' of data only when it's needed, which is perfect solution for a problem. A user scroll the list, and SwiftUI load data by batches when required.
Here is what I have (simplified):
ContextView.swift
struct ContentView: View {
@FetchRequest private var items: FetchedResults<Item>
init() {
_items = FetchRequest<Item>(fetchRequest: request())
}
var body: some View {
List(items) {
Text($0.name)
}
}
func request() -> NSFetchRequest<Item> {
let request = Item.fetchRequest()
request.sortDescriptors = []
request.fetchBatchSize = 5
return request
}
}
The problem: @FetchRequest loads all the records at the same time without batching and/or it does work but retrieves all the batches at the same time and defeating the whole purpose of batch retrieving.
I tried actually loading 1 mil rows and takes a lot of time to show the view (as it is retrieving and preparing all 1 mil rows of data). If '.fetchBatchSize' worked it will load only the first 5 and will load slowly as the list scrolls.
*Note: I know there is .fetchLimit & .fetchOffset, but it would require to implement a separate logic *
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
