NSPredicate和CoreData? [英] NSPredicate and CoreData?
本文介绍了NSPredicate和CoreData?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果直接添加到谓词,查询就可以正常工作
NSPredicate * predicate = [NSPredicate predicateWithFormat:@author == %@,author];
[request setPredicate:predicate];
[self.managedObjectContext executeFetchRequest:request error:nil];
如果创建并且传递到谓词
有没有解决方案?我不是将谓词本身传递给方法
作者是NSManagedObject的子类
***由于未捕获异常而终止应用程序'NSInvalidArgumentException',原因:'无法解析格式字符串%@'
[self fetchObjectsWithQuery :[NSString stringWithFormat:@author ==%@,author];
- (void)fetchObjectsWithQuery:(NSString *)query
{
NSPredicate * predicate = [NSPredicate predicateWithFormat:@%@,query];
[request setPredicate:predicate];
[self.managedObjectContext executeFetchRequest:request error:nil];
}
解决方案
/ p>
NSString * query = [NSString stringWithFormat:@author ==%@,author] //(1)
和
NSPredicate * predicate = [NSPredicate predicateWithFormat:@author ==%@,author]
特别是占位符%@和%K有不同的含义。
(1)产生
author ==<作者对象的文本描述>
您不能在
中使用 NSPredicate * predicate = [NSPredicate predicateWithFormat:@%@,query];
因此,您不能将谓词预先格式化为字符串。另一个例子来说明问题:
[NSPredicate predicateWithFormat:@author == nil]
$ NSPredicate predicateWithFormat:%@,@author == nil]
p>
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];
}
解决方案 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.
这篇关于NSPredicate和CoreData?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文