Using NSPredicate how to filter value from core da

2019-09-16 17:05发布

问题:

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];

but i cant do this plz help me.

回答1:

You need not enclose the attribute name in quotation marks:

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

or better

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

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


(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];