使用NSPredicate如何从核心数据中过滤值

使用NSPredicate如何从核心数据中过滤值

本文介绍了使用NSPredicate如何从核心数据中过滤值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个实体&三个属性称为名称,版本,公司。
i希望过滤公司属性中的值,如快餐。

I have one entity & three Attribute called as name, version, Company.i want to filter value from company attribute like as "Fast Food".

    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Device" inManagedObjectContext:managedObjectContext];
    [request setEntity:entity];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"('company' contains[c] 'Fast Foood')"];
    [request setPredicate:predicate];
    NSLog(@"Pre %@",predicate);

    NSError *error = nil;
    NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
    if (mutableFetchResults == nil) {
        // Handle the error.
    }

    // Set self's events array to the mutable array, then clean up.
    [self setDataarr:mutableFetchResults];

但我不能这样做PLZ帮助我。

but i cant do this plz help me.

推荐答案

您无需将属性名称括在引号中:

You need not enclose the attribute name in quotation marks:

[NSPredicate predicateWithFormat:@"company CONTAINS[c] 'Fast Foood'"];

或更好

[NSPredicate predicateWithFormat:@"company CONTAINS[c] %@", @"Fast Foood"];

Btw。:您的谓词搜索Fast Foood,而不是Fast Food。

Btw.: Your predicate searches for "Fast Foood", not for "Fast Food".

(回应你的评论)你应该定义实体 Category Dishes 具有一对多的关系:

(In response to your comments) You should define entities Category and Dishes with a one-to-many relationship:

现在,您可以通过以下获取请求找到给定类别的所有菜肴:

Now you can find all dishes for a given category with the following fetch request:

NSString *catName = @"Desert";
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Dish"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"category.name = %@", catName];
[request setPredicate:predicate];

这篇关于使用NSPredicate如何从核心数据中过滤值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 02:12