Reputation: 77596
The query works fine if directly added to a predicate
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"author == %@", author];
[request setPredicate:predicate];
[self.managedObjectContext executeFetchRequest:request error:nil];
The query doesn't work if created and then passed to a predicate
Is there a solution? I rather not pass the predicate itself to the method
Author is a subclass of NSManagedObject
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unable to parse the format string "%@"'
[self fetchObjectsWithQuery:[NSString stringWithFormat:@"author == %@", author];
- (void)fetchObjectsWithQuery:(NSString *)query
{
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%@", query];
[request setPredicate:predicate];
[self.managedObjectContext executeFetchRequest:request error:nil];
}
Upvotes: 1
Views: 767
Reputation: 539685
Format strings work differently in
NSString *query = [NSString stringWithFormat:@"author == %@", author] // (1)
and
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"author == %@", author]
In particular the placeholders "%@" and "%K" have different meanings.
(1) produces a string of the form
"author == <textual description of author object>"
which you cannot use in
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%@", query];
So you cannot pre-format predicates as strings. Another example to demonstrate the problem:
[NSPredicate predicateWithFormat:@"author == nil"]
works, but
[NSPredicate predicateWithFormat:"%@", @"author == nil"]
does not.
Upvotes: 2
Reputation: 31782
There's no good reason not to create and pass around NSPredicate
objects. There are ways to do exactly what you want to do, but they are either less expressive than just using predicates or will require you to duplicate the logic underlying NSPredicate
.
Upvotes: 0