简体   繁体   中英

Accessing objects using NSPredicate from Core Data

I tried to find answer to my simple question with no luck... I'm working on CoreData and i have two entities lets take an example of "Photo and Photographer" one to many relationship, means one photographer can have multiple photos... Now i did store objects using

[NSEntityDescription insertNewObjectForEntityForName...]

I'm having issues retrieving "all photos" from a specific photographer. I'm using this code

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Photographer"];
fetchRequest.predicate = [NSPredicate predicateWithFormat:@"name = %@",@"photographerName"];
fetchRequest.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"timeStamp" ascending:YES]];

this code is returning photographer however i only need ALL photos taken by this photographer. I'm new to CoreData, i'm not sure if i should be using "Photos" entity?

thanks in advance.

Your fetch request should request Photo entity.

Then, in your predicate, you can specify the name of the photographer like so:

fetchRequest.predicate = [NSPredicate predicateWithFormat:@"photographer.name = %@",@"photographerName"];

Or better yet, it would be much faster to first get the photographer object, and then test the relationship in the predicate:

Photographer* photographer = ... //Get required photographer here
fetchRequest.predicate = [NSPredicate predicateWithFormat:@"photographer = %@", photographer];

Use this to sort the photographer.photos array.

NSSortDescriptor *sortKey = [[NSSortDescriptor alloc] initWithKey:@"timestamp" ascending:YES];
NSArray *sorters = [NSArray arrayWithObject:sortKey]; 
NSArray *sortedArray = [photographer.photos sortedArrayUsingDescriptors:sorters];

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