开发者

Using NSPredicate to get an array of Core Data objects?

开发者 https://www.devze.com 2023-01-26 04:59 出处:网络
Say I have a Core Data entity called Person. How would I get an NSArray of Persons whose properties match certain values? For instance someone of a particular age, height, or weight... or someone with

Say I have a Core Data entity called Person. How would I get an NSArray of Persons whose properties match certain values? For instance someone of a particular age, height, or weight... or someone with a whose height,weight and age are specific values...

Can I use an NSPredicate like so:

NSPredicate *pred = 
[NSPredicate predicateWithFormat:
@"(age == 25) OR (height_in_cms == 185) OR (age == 30 AND height_in_cms == 170 AND weight_in_kgs == 80)"; 
// All p开发者_Python百科roperties are NSNumber


I'm not an expert on the syntax for predicateWithFormat:, but you have the basic gist. You can find details on the format in Apple's Predicate Programming Guide. If you're asking what to do with the predicate once you have it, here is a snippet that shows you the steps:

// Create a fetch request.
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

// Set the entity for the fetch request.
NSEntityDescription *entity = [NSEntityDescription entityForName:@"EntityName" inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];
[entity release];

// Set the predicate for the fetch request.
[fetchRequest setPredicate:predicate];

// Perform the fetch.
NSError *error;
NSArray *array = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
[fetchRequest release];

If you want the results to be sorted, you can pass an array of sort descriptors to the fetch request using setSortDescriptors: prior to executing the fetch.


You can follow the given statement if you have these value in a variable.

[fetchResults filterUsingPredicate:[NSPredicate predicateWithFormat:@"age == %i OR hieght== %i AND weight==%i",age,height,weight]];

And also your approach is correct in case for specific values but your statement having syntax error so maintain proper syntax

0

精彩评论

暂无评论...
验证码 换一张
取 消