简体   繁体   中英

Using NSPredicate how to filter value from core data

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM