I have a single Entity in CoreData mimicking a MySQL database table with the following structure:
Photo
abv Double
photoId Integer16
photographer String
isActive Boolean
lastUpdated Data
name String
I can run the following SQL statement to get my desired result set:
SELECT `photographerName`, COUNT(`photographerName`)
FROM `Photos`
WHERE `isActive` LIKE 1
GROUP BY `photographerName`
ORDER BY `photographerName`
What combination of NSFetchRequest, NSSortDescriptor, NSPredicate, NSExpressionDescription can I use to achieve the same results in iOS?
I am using the following:
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Photo"];
NSSortDescriptor *photographerSortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"photographer" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)];
NSPredicate *onlyActivePhotos = [NSPredicate predicateWithFormat:@"isActive == 1"];
request.sortDescriptors = @[photographerSortDescriptor];
request.predicate = onlyActivePhotos;
self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:nil];
Which gets me the isActive fine, but returns a row for every Photo, not Photographer.
Or… should I be splitting this into two Entities? For example, Photographer with a one-to-many relationship to Photos?
First, it is certainly better and more flexible design to have a relationship
Photo–Photographer.However, what you want can also be achieved. You can only get the photo entities, so after you have to filter the resulting array to just return your photographer names.
As you can see, this is quite cumbersome. Also, you have lost the information which photos are associated with each photographer.
So please go with the relationship. After all, Core Data is an object graph, not a database wrapper.