问题
I am trying to search in CoreData for an object that matches both a recordId and a string name, but it doesn't always find the object. For example, I an searching for an object with id 1000 and name "The Brown Family" (note the 2 spaces between "The" and "Brown"). If I use:
NSPredicate *pred = [NSPredicate predicateWithFormat:@"(recordId == %@") AND (name like[cd] %@)", recordId, name];
with recordId=1000 and name="The Brown Family", the fetch request returns nil. If I use:
NSPredicate *pred = [NSPredicate predicateWithFormat:@"(recordId == %@"), recordId];
with recordId=1000, it finds the object. If I print the object's name property, I get "The Brown Family". So the object is there with the correct id and name, but my fetchRequest fails. What am I doing wrong?
回答1:
You might need to enclose the value in single quotes...
NSPredicate *pred = [NSPredicate predicateWithFormat:@"(recordId == %@) AND (name like[cd] '%@')", recordId, name];
回答2:
Sorry but I realise what the problem is now! The name I was searching for had a trailing space after it. So I was looking for say "Toby " whereas "Toby" was stored in Coredata. Sorry for wasting everyone's time.
来源:https://stackoverflow.com/questions/34633764/nspredicate-execurefetchrequest-not-working-possibly-due-to-spaces-in-string