xcodecore-dataswiftuinsfetchrequest

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
        }
    }
}


Solution

  • 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)
    }