Reputation: 127
I want to search a string in my DB and it keeps returning all records from core data. The other questions I saw here didn't work. Suggestions?
var users:[Users] = []
override func viewDidLoad() {
super.viewDidLoad()
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let myrequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Users")
let predicate = NSPredicate(format: "name = '%@'", "alex")
myrequest.predicate = predicate
do{
users = try context.fetch(myrequest) as! [Users]
}catch{
print("error")
}
}
Upvotes: 1
Views: 3026
Reputation: 127
it's working now. this is the final code. Maybe it will help someone in the future :) thanks for the help guys.
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let query:NSFetchRequest<Users> = Users.fetchRequest()
let key = "alex"
let predicate = NSPredicate(format: "name contains[c] %@", key)
query.predicate = predicate
do{
users = try context.fetch(query)
print(users.count)
}catch{
print("error")
}
Upvotes: 4
Reputation: 1024
try to do this in do case
users = try context.fetch(Users.fetchRequest())
Upvotes: 0
Reputation: 58019
You should not use single quotes in your predicate. Try with this:
let predicate = NSPredicate(format: "name = %@", "alex")
myrequest.predicate = predicate
Upvotes: 0