NSPredicate and CoreData?

╄→尐↘猪︶ㄣ 提交于 2019-12-11 05:41:49

问题


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];
}

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/12665001/nspredicate-and-coredata

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!