0

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?

guinnessman
  • 433
  • 5
  • 15

2 Answers2

1

You might need to enclose the value in single quotes...

NSPredicate *pred = [NSPredicate predicateWithFormat:@"(recordId == %@) AND (name like[cd] '%@')", recordId, name];
Flexicoder
  • 8,251
  • 4
  • 42
  • 56
  • I tried that but it made no difference. Thanks for the suggestion though. – guinnessman Jan 06 '16 at 15:25
  • I looked through my results again. There are hundreds of names stored. The ones that I had spotted with problems before had double spaces etc. in the name string. However, looking through them again, I can see ones as simple as "Toby". So the spaces part is a red herring I think. – guinnessman Jan 06 '16 at 15:28
  • Silly question if you know the unique `recordId` (I assume its unique), why are you matching on name as well? – Flexicoder Jan 06 '16 at 16:08
  • Usually the recordId would be enough. But there are occasions where the recordId changes e,g, going from device to device. – guinnessman Jan 06 '16 at 17:58
  • 1
    `name like[cd] '%@'` is wrong, that will search only for the verbatim string `"%@"`. – Martin R Jan 06 '16 at 18:42
0

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.

guinnessman
  • 433
  • 5
  • 15