Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 964
simibac Avatar asked Dec 23 '19 05:12

simibac


People also ask

What is the use of @fetchrequest in SwiftUI?

The @FetchRequest property wrapper in your SwiftUI view. A SwiftUI View that displays the results of the executed fetch request. The following code snippets provide you an example of how to weave all three components together. Comments with ❇️ symbols will explain the details inline.

How to limit query results in SQL?

In this article, we will learn how to limit query results in SQL using different examples. A MySQL supports the LIMIT clause to select a limited number of records. If we want to LIMIT the number of results that will return us a number of rows then we simply use the LIMIT command. Use the below SQL statement to create a database called geeks:

How do I fetch data from core data in SwiftUI?

With most Core Data apps, you’re going to see a call to fetch (_:) somewhere in your code. This happens “behind the scenes” when you use the @FetchRequest property wrapper in your SwiftUI view.

What is the @environment in SwiftUI?

@Environment (\.managedobjectcontext) must be assigned before the View is initialized for @FetchRequest to work. You can refer to my introduction to using Core Data with SwiftUI to review all of the steps in one spot.


1 Answers

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)
}
like image 64
Asperi Avatar answered Nov 15 '22 09:11

Asperi