我正在尝试编写一种方法,该方法尝试使用变量(作为 NSXMLParser 的一部分)基于谓词检索对象。代码如下所示:
我在类中定义了这些变量:
@property (strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@property (strong, nonatomic) NSString *model;
@property (strong, nonatomic) NSString *element;
现在在方法中,我这样设置请求:
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:self.model inManagedObjectContext:self.managedObjectContext];
[request setEntity:entity];
现在的挑战 - 我希望能够做到的是:
// DOES NOT WORK
[request setPredicate:[NSPredicate predicateWithFormat:@"%@ == %@", self.element,string]];
但这不会返回任何结果。经过一番摸索之后,我注意到这确实有效:
if ( [self.element isEqualToString:@"name"] ) {
[request setPredicate:[NSPredicate predicateWithFormat:@"name == %@", string]];
}
这告诉我我的 self.element
设置正确(我认为?)但是谓词不喜欢表达式的左侧是变量。
我也试过:
[request setPredicate:[NSPredicate predicateWithFormat:@"%s == %@", [self.element UTF8String],string]];
...只是为了看看它是否更喜欢一个字符串。我也做不到。
我正在尝试的是可能的吗?我已经尽可能多地阅读了 Core Data 文档,但我找不到任何以这种方式执行的示例代码,但我也没有找到任何可以证明这是不可能的内容。
编辑: 现在是工作代码:
[request setPredicate:[NSPredicate predicateWithFormat:@"%K == %@", self.element,string]];
最佳答案
如果您以前没有做过,请阅读 Predicate Programming Guide你可以找到关于谓词的一切。
现在,如果我没理解错的话,您想在两个字符串之间创建一个谓词,但第一个不是已定义的字符串,但它可以更改。
我以前没有使用过它们,但我相信您可以通过使用具有动态属性名称的谓词来解决您的问题。
这里来自文档:
Dynamic Property Names
Because string variables are surrounded by quotation marks when they are substituted into a format string using%@
, you cannot use%@
to specify a dynamic property name—as illustrated in the following example.NSString *attributeName = @"firstName"; NSString *attributeValue = @"Adam"; NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%@ like %@", attributeName, attributeValue];
The predicate format string in this case evaluates to "firstName" like "Adam".
If you want to specify a dynamic property name, you use
%K
in the format string, as shown in the following fragment.predicate = [NSPredicate predicateWithFormat:@"%K like %@", attributeName, attributeValue];
The predicate format string in this case evaluates to firstName like "Adam" (note that there are no quotation marks around firstName).
更多信息也可以在这里找到:Predicate Format String Summary .
关于ios - 在核心数据谓词中使用元素名称变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9261862/