0

I have a problem where I am inserting entities A in a context. Right after I insert all of the entities A I execute a fetch request on the context:

NSEntityDescription* entity = [NSEntityDescription entityForName:@"A" inManagedObjectContext:ctx];
NSFetchRequest* fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity:entity];
NSError* fetchError;
NSArray* results = [ctx executeFetchRequest:fetchRequest error:&fetchError];

This code above is able to get all of them and I can see them in the NSLog...

Right after on the same context I try to fetch all entities A that have age = 5, like this: (I assign "age" to the attirbute and a NSString @"5" to the value)

NSEntityDescription* entity = [NSEntityDescription entityForName:@"A" inManagedObjectContext:ctx];
NSFetchRequest* fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity:entity];
NSPredicate *filter = [NSPredicate predicateWithFormat:@"%K == %@",attr,value];
[fetchRequest setPredicate:filter];
NSError* fetchError;
NSArray* results = [ctx executeFetchRequest:fetchRequest error:&fetchError];

THE PROBLEM IS that even though the NSLog shows an entity A with age 5 this last fetch request returns always null! Nothing.

Any suggestions? Why fetching all of them shows entities with age 5 and filtering for age 5 only does not work right after on the same context?

Thanks

zumzum
  • 17,984
  • 26
  • 111
  • 172
  • What type is age in the model? – Jody Hagins Apr 14 '12 at 20:36
  • NSNumber (Integer 64) , also, I just found out that if I hard code the predicate to be @"age == 5" then it works. I'm confused now. – zumzum Apr 14 '12 at 20:43
  • %@ with a string argument inserts quotation marks for a string comparison. If the data is not a string, it will not compare... which is why I asked the type... – Jody Hagins Apr 14 '12 at 21:13

1 Answers1

3

Try setting age to an instance of NSNumber initalized to 5 rather than the NSString @"5".

tronbabylove
  • 1,102
  • 8
  • 12
  • Worked. darn, so, I thought that I could always provide a string in an NSPredicate... I guess because age is an NSNumber then it makes sense that your suggestion works, but, COULD YOU maybe give me a hint why I can't just pass in an NSString in this case? What am I missing here? Thanks!! – zumzum Apr 14 '12 at 20:55
  • When you pass a string as the argument to a predicate, it automatically converts it to a "string" with quotes, which does not compare to a value of 5. – Jody Hagins Apr 14 '12 at 21:12