gpt4 book ai didi

objective-c - NSPredicate 和 CoreData?

转载 作者:行者123 更新时间:2023-11-29 11:08:31 27 4
gpt4 key购买 nike

如果直接添加到谓词,查询工作正常

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"author == %@", author];
[request setPredicate:predicate];
[self.managedObjectContext executeFetchRequest:request error:nil];

如果创建然后传递给谓词,查询将不起作用

有解决办法吗?我宁愿不将谓词本身传递给方法

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

最佳答案

格式字符串的工作方式不同

NSString *query = [NSString stringWithFormat:@"author == %@", author] // (1)

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"author == %@", author]

特别是占位符“%@”和“%K”具有不同的含义。

(1) 产生一个 string 的形式

"author == <textual description of author object>"

你不能在其中使用

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%@", query];

因此您不能将谓词预格式化为字符串。另一个演示问题的例子:

[NSPredicate predicateWithFormat:@"author == nil"]

有效,但是

[NSPredicate predicateWithFormat:"%@", @"author == nil"]

没有。

关于objective-c - NSPredicate 和 CoreData?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12665001/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com