simibac
simibac

Reputation: 8570

How to limit the number of results in a FetchRequest in SwiftUI

How can I limit the size of the retrieved FetchedResults when making a FetchRequest to CoreData?

struct ContentView: View {
    var fetchRequest:FetchRequest<Kana>

    init(){
        fetchRequest = FetchRequest<Kana>(entity: Kana.entity(), sortDescriptors: [], predicate: NSPredicate(format: "alphabet == %@", "hiragana"))
    }

    var body: some View {
        List{
            Text("10 Kanas")
            // Display 10 Kanas
        }
    }
}

Upvotes: 8

Views: 3385

Answers (1)

Asperi
Asperi

Reputation: 257563

You need to create FetchRequest with NSFeatchRequest using corresponding initialiser, as shown below

init() {
    let request: NSFetchRequest<Kana> = Kana.fetchRequest()
    request.fetchLimit = 10
    request.predicate = NSPredicate(format: "alphabet == %@", "hiragana")
    fetchRequest = FetchRequest<Kana>(fetchRequest: request)
}

Upvotes: 12

Related Questions