Core Data String Queries Using NSPredicate In Swift
Learn how to find an exact string, regex search, and more in Core Data.
This post presents NSFetchRequest examples with NSPredicate that take String arguments. Examples will be shown for the following queries:
- Exact String Match With A NSPredicate
- Contains String With A NSPredicate
- NSPredicate Regex Search
- Search For Matches That Begin With String
- Search For Matches That End With String
The examples below will query a Core Data database with a single entity description, Person. Person has a single attribute name, a String.
Exact String Match With A NSPredicate
The LIKE keyword in an NSPredicate will perform an exact string match.
let query = "Rob"
let request: NSFetchRequest<Person> = Person.fetchRequest()
request.predicate = NSPredicate(format: "name LIKE %@", query)
// The == syntax may also be used to search for an exact match
request.predicate = NSPredicate(format: "name == %@", query)
Additionally, the c and d modifiers can be used to perform a case-insensitive and diacritic insensitive (c would match ç as well) search:
let query = "Rob"
let request: NSFetchRequest<Person> = Person.fetchRequest()
request.predicate = NSPredicate(format: "name LIKE[cd] %@", query)
Contains String With A NSPredicate
The CONTAINS keyword in an NSPredicate will perform a contains string match.
let query = "Rob"
let request: NSFetchRequest<Person> = Person.fetchRequest()
request.predicate = NSPredicate(format: "name CONTAINS %@", query)
The c and d modifiers can also be used with CONTAINS to perform a case-insensitive. and diacritic insensitive (c would match ç as well) search.
NSPredicate Regex Search
The MATCHES keyword in an NSPredicate is used to perform a regular expression search.
let query = "??bert*"
let request: NSFetchRequest<Person> = Person.fetchRequest()
request.predicate = NSPredicate(format: "name MATCHES %@", query)
Search For Matches That Begin With String
The BEGINSWITH keyboard in an NSPredicate is used to perform a search for strings that begin with a specific substring.
let query = "R"
let request: NSFetchRequest<Person> = Person.fetchRequest()
request.predicate = NSPredicate(format: "name BEGINSWITH %@", query)
Search For Matches That End With String
The ENDSWITH keyboard in an NSPredicate is used to perform a search for strings that end with a specific substring.
let query = "R"
let request: NSFetchRequest<Person> = Person.fetchRequest()
request.predicate = NSPredicate(format: "name BEGINSWITH %@", query)
Find Strings In Core Data
That’s it! With LIKE, CONTAINS, MATCHES, BEGINSWITH, and ENDSWITH you can perform a wide array of queries in Core Data with String arguments.