I'm trying to develop an app for iPhone using Core Data and I'm using a very basic predicate to grab objects. (i.e. attribute_name==string)
I've checked the model to make sure the attribute names are correct and I know from this SO question that RHS means "Right Hand Side," which leads me to the "string" part. I'm creating the format string using
NSString *predicateString = [NSString stringWithFormat:@"attribute_name==%@", string];
Then to fetch, I'm using this:
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:_entityName inManagedObjectContext:managedObjectContext];
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity:entityDescription];
NSPredicate *predicate = [NSPredicate predicateWithFormat:predicateString];
[request setPredicate:predicate];
NSError *error = nil;
NSArray *array = [managedObjectContext executeFetchRequest:request error:&error];
What am I missing? What could cause this error to occur?
Thanks.
You need to quote the string if you really want to use the NSString stringWithFormat:
message or you could use the NSPredicate predicateWithFormat:
message with the formatting and arguments because it will "do the right thing" with the rhs in your situation (I would suggest that you use the NSPredicate
method without the quotes)
NSString *predicateString = [NSString stringWithFormat:@"attribute_name==\"%@\"", string];
You're doing this wrong. You should not be creating a format string.
I'm guessing (based on your reaction to @Brent's answer) that you're doing something like this:
NSString *predicateString = [NSString stringWithFormat:@"foo == \"%@\"", bar];
NSPredicate *p = [NSPredicate predicateWithFormat:predicateString];
Don't do that.
Do this instead:
NSPredicate *p = [NSPredicate predicateWithFormat:@"foo == %@", bar];
The first will fail if bar
happens to contain a "
character. The second will not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With