skip to content

In Core Data, how do you write the NSPredicate for a species search-as-you-type filtered by region and dates, and why never interpolate the typed text?

level: middleimportance: must knowfreq 75%

answer

  1. arguments, not string building
  2. %@ for values, %K for key paths
  3. [c] for case, [d] for diacritics
  4. NSCompoundPredicate for optional filters
  5. an apostrophe in the search text

basics

~20 s

Pass every value as an argument: species CONTAINS[cd] %@ for the text, region IN %@ for regions and seenAt >= %@ AND seenAt < %@ for dates, joined by NSCompoundPredicate. Interpolated text breaks parsing, and an apostrophe crashes the app.

solid answer

~40 s

I build it from arguments, never from string concatenation. `%@` substitutes a value and quotes it for me; `%K` substitutes a key path, so `%K == %@` with "region" works, while `%@ == %@` just compares two strings. For the search I use `species CONTAINS[cd] %@` (or `BEGINSWITH[cd]`): `[c]` ignores case and `[d]` ignores diacritics, so "cafe" finds "Café". Regions go in as an array with `region IN %@`, the date range as `seenAt >= %@ AND seenAt < %@` with `NSDate` arguments. I add only the filters that are active and combine them with `NSCompoundPredicate(andPredicateWithSubpredicates:)`. Interpolating the text means a name like O'Brien leaves the format string unparseable: `NSPredicate(format:)` raises `NSInvalidArgumentException`, which Swift cannot catch, so the app crashes, and crafted text could change what the predicate matches.

code

swift · 21 lines
swift
import CoreData

@objc(Sighting)
final class Sighting: NSManagedObject {
    @NSManaged var species: String
    @NSManaged var region: String
    @NSManaged var seenAt: Date
}

func sightingPredicate(search: String, regions: [String], from start: Date, to end: Date) -> NSPredicate {
    var parts: [NSPredicate] = [
        NSPredicate(format: "%K IN %@", #keyPath(Sighting.region), regions),
        NSPredicate(format: "seenAt >= %@ AND seenAt < %@", start as NSDate, end as NSDate)
    ]
    let text = search.trimmingCharacters(in: .whitespacesAndNewlines)
    if !text.isEmpty {
        // The typed text is an argument, never part of the format string.
        parts.append(NSPredicate(format: "species CONTAINS[cd] %@", text))
    }
    return NSCompoundPredicate(andPredicateWithSubpredicates: parts)
}

go deeper

for a junior

Recall the two tokens: %@ substitutes a value and quotes it, %K substitutes an attribute name, and [cd] makes string comparisons ignore case and accents.

for a middle

Explain why arguments beat interpolation, the uncatchable parse exception and the injection risk, and compose optional filters with NSCompoundPredicate instead of one branching format string.

for a senior

Spot the review-time traps: quoted %@, %@ in a key position, block predicates on SQLite stores, inclusive BETWEEN on dates, and an empty compound that matches everything.

for a principal

Turn it into a codebase rule: predicates only through builders that take arguments, a lint check for interpolated format strings, and tests that run every builder against a SQLite store.

## Why format strings take arguments An **`NSPredicate`** is a logical condition. With a SQLite store, Core Data turns the predicate of a fetch request into a query against the database, so a predicate is effectively a small program. The common way to write one is a **format string** parsed by `NSPredicate(format:_:)`, with the variable parts passed as **arguments**, much like `String(format:)`. The argument mechanism matters because the parser sees the format string as syntax. If user text is pasted into that string, an apostrophe, a quote or an operator in the text becomes syntax too. `NSPredicate(format: "species == '\(text)'")` with the text `O'Brien` produces a string the parser cannot read, and the initializer raises an Objective-C `NSInvalidArgumentException`. Swift's `do`/`catch` cannot catch it, so the app terminates. Text that parses cleanly is worse in a quieter way: it can add conditions of its own. Typing `x' OR species != 'y` turns the same line into `species == "x" OR species != "y"`, which matches every sighting. ## The substitution tokens | Token | Substitutes | Example | |---|---|---| | `%@` | an object value: `String`, `NSNumber`, `NSDate`, an array | `region == %@` | | `%K` | a **key path** (attribute name) | `%K == %@` with `"region"`, `"North"` | | `$NAME` | a variable filled later with `withSubstitutionVariables(_:)` | `region == $REGION` | - `%@` adds the quoting itself. Writing `'%@'` in single quotes turns it into the literal text `%@`, so the predicate silently matches nothing. - `%@` in the key position does not name an attribute: `%@ == %@` with `"region"`, `"North"` compares two string constants and matches nothing. Use `%K`, or `#keyPath(Sighting.region)` passed to `%K`, when the attribute is chosen at runtime. - `%@` expects an object, so wrap numbers as `NSNumber(value:)` and pass dates as `NSDate`; a bare Swift `Int` handed to `%@` is not an object, and the app crashes. ## Operators a search screen needs - **`==`, `!=`, `<`, `<=`, `>`, `>=`** for exact values and ranges. - **`BEGINSWITH`, `ENDSWITH`, `CONTAINS`** for substrings; **`LIKE`** with `*` and `?` wildcards; **`MATCHES`** for a regular expression. - **`[c]`** makes a string comparison case-insensitive and **`[d]`** diacritic-insensitive; `[cd]` does both, so `CONTAINS[cd] "cafe"` matches "Rotkehlchen Café" while plain `CONTAINS` does not. - **`IN %@`** with an array tests membership: `region IN %@` with `["North", "East"]`. - **`BETWEEN {lower, upper}`** is inclusive at both ends. For dates, a half-open pair, `seenAt >= %@ AND seenAt < %@`, is clearer and never counts the boundary twice when ranges are consecutive days. - **`AND`, `OR`, `NOT`** combine conditions inside one string. ## Combining optional filters A search screen has filters that come and go: no search text yet, all regions selected. Building one format string with branches gets fragile. Instead: 1. Create one small predicate per active filter. 2. Put them in an array. 3. Wrap them with `NSCompoundPredicate(andPredicateWithSubpredicates:)`, or the `or` and `not` variants. An AND compound with **no** subpredicates evaluates to true, so a fetch whose predicate is an empty AND filters nothing and the screen shows everything rather than nothing. Since iOS 17 Foundation can also convert a `#Predicate` value into an `NSPredicate` with `NSPredicate(_:)`; that macro is taught with SwiftData's fetching. ## What the SQLite store cannot run The predicate has to be translatable for the store. A **block predicate**, `NSPredicate { object, _ in ... }`, can filter arrays in memory, but Foundation's header says Core Data supports block predicates only in the in-memory and atomic stores, not the SQLite store. On a SQLite-backed fetch it raises `NSInvalidArgumentException` with "Unknown predicate type for predicate: BLOCKPREDICATE". Express the condition in format syntax, or fetch and then filter the array. ## Mistakes worth avoiding - Interpolating or concatenating user text into the format string. - Quoting `%@`, or using `%@` where an attribute name belongs. - Forgetting `[d]`, so accented names never match a plain-keyboard search. - Sending a block predicate to a SQLite-backed fetch. - Rebuilding one giant format string per combination of filters instead of composing small predicates. - Debugging by guesswork: printing `predicateFormat` shows how the parser read the predicate, quoting included, though Foundation does not promise it matches the original string exactly.

  • Why does NSPredicate(format: "species == '%@'", "Robin") never match the Robin sighting?
    The single quotes make the parser read `'%@'` as a string literal, so the predicate compares species with the two characters `%@` and the argument is never used. `%@` already quotes the value it substitutes, so the correct form is `species == %@` with no quotes.
  • What happens when a SQLite-backed Core Data fetch is given a block-based NSPredicate?
    The fetch raises `NSInvalidArgumentException` with "Unknown predicate type for predicate: BLOCKPREDICATE", because the SQLite store cannot translate a closure into its query; Foundation's header limits block predicates in Core Data to the in-memory and atomic stores. Write the condition in format syntax, or fetch first and filter the resulting array in memory.
  • Is BETWEEN a good choice for the date-range filter on the sightings screen?
    `BETWEEN {lower, upper}` includes both bounds, so ranges of consecutive days that share a midnight boundary count a sighting at that instant twice. A half-open pair, `seenAt >= %@ AND seenAt < %@`, avoids that and reads clearly, so it is the usual choice for dates; `BETWEEN` suits inclusive numeric ranges such as a bird count from 2 to 3.

  • Wrap %@ in single quotes whenever the argument is a string.
  • Interpolating the search text into the format string is fine once it is trimmed.
  • %@ can stand in for an attribute name as well as for a value.
  • CONTAINS[c] already ignores accents such as the é in Café.
  • A block-based NSPredicate works with every Core Data store type.
  • An AND NSCompoundPredicate with no subpredicates matches nothing.