ios - 在核心数据谓词中使用元素名称变量

标签 ios core-data predicate

我正在尝试编写一种方法,该方法尝试使用变量(作为 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/

相关文章:

ios - Touch Id提示按钮本地化

ios - 当我需要首次加载屏幕时如何组织 Controller 和 View

swift - 核心数据 : computed property in extension is "called" when object is saved

swift - RealmSwift + 多谓词

mysql - 如果我们使用谓词对 View 进行查询,数据库服务器是否会将谓词推送到 View 的下划线查询?

objective-c - 为图像添加色调

iphone - 如果在 iPad 上查看,iOS 6 Smart Banner for Phone 应用程序会显示在网站上吗?

ios - NSPredicate ANY 多列

ios - CoreData执行后台任务冲突

java - 为什么我们需要Java中的Predicate函数式接口(interface)?