var nsPredicate : NSPredicate?
Overview 概要
You initialize a Fetch
with an optional predicate and sort descriptors, either explicitly or using a configured NSFetch
. Later, you can dynamically update the predicate and sort parameters using the request’s configuration structure.
You access or bind to a request’s configuration components through properties on the associated Fetched
instance.
Configure Using a Binding
Get a Binding
to a fetch request’s configuration structure by accessing the request’s projected
, which you do by using the dollar sign ($
) prefix on the associated results property. For example, you can create a request for Quake
entities — a managed object type that the Loading and Displaying a Large Data Feed sample code project defines — that initially sorts the results by time:
SortDescriptor(\.time, order: .reverse)]) (sortDescriptors: [
private var quakes: FetchedResults<Quake>
Then you can bind the request’s sort descriptors, which you access through the quakes
result, to those of a Table
instance:
Table(quakes, sortOrder: $quakes.sortDescriptors) {
TableColumn("Place", value: \.place)
TableColumn("Time", value: \.time) { quake in
Text(quake.time, style: .time)
}
}
A user who clicks on a table column header initiates the following sequence of events:
The table updates the sort descriptors through the binding.
The modified sort descriptors reconfigure the request.
The reconfigured request fetches new results.
SwiftUI redraws the table in response to new results.
Set Configuration Directly
If you need to access the fetch request’s configuration elements directly, use the ns
and sort
or ns
properties of the Fetched
instance. Continuing the example above, to enable the user to dynamically update the predicate, declare a State
property to hold a query string:
private var query = ""
Then add an on
modifier to the Table
that sets a new predicate any time the query changes:
.onChange(of: query) { value in
quakes.nsPredicate = query.isEmpty
? nil
: NSPredicate(format: "place CONTAINS %@", value)
}
To give the user control over the string, add a Text
in your user interface that’s bound to the query
state:
TextField("Filter", text: $query)
When the user types into the text field, the predicate updates, the request fetches new results, and SwiftUI redraws the table.