2
votes

I am new to core data and i dont know how to write query like this using core data.

I hav two entities Album and Songs in schema. Album is related to Song by one many relationship and relationship name is tracks. I hav written query to fetch all albums and that is working well. But now i want to make little change in that so that i will not get albums having 0 songs. I tried to set predicate on request like

tracks.@count != 0 
tracks.@count != nil

but this is not working may be because of faulting ?. Do i need to prefetch relationship or something. I dont want to add attribute songCount in Album and i just need count song. What is best way to write query like this ? thanks in advance !

Code -

NSFetchRequest *request = [[NSFetchRequest alloc] init];
 request.entity = [NSEntityDescription entityForName:@"Album" inManagedObjectContext:[self managedObjectContext]];
 NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES selector:@selector(caseInsensitiveCompare:)];
 [request setSortDescriptors:[NSArray arrayWithObject:sort]];  
 NSPredicate *albumPredicate = [NSPredicate predicateWithFormat:@"tracks.@count > 0"];
 [request setPredicate:albumPredicate];

This is what i got on console after turning on Debug mode

CoreData: sql: SELECT 0, t0.Z_PK FROM ZALBUM t0 WHERE (SELECT COUNT(*) FROM ZTRACK t1 WHERE (t0.Z_PK = t1.ZALBUM) ) > ? ORDER BY t0.ZNAME COLLATE NSCollateNoCase 

whats wrong in code ?

2
tracks.@count != 0 should just work. - Martin R
It'd help if you'd include your code and a better description of the problem. this is not working really isn't enough to let us help you figure out why it's not working. - Caleb

2 Answers

2
votes

Have you tried this:

[NSPredicate predicateWithFormat:@"tracks.@count>0"];

EDIT:

Try turning on SQLDebug and have a look at the generated SQL statement. You will find the statement in your console as your fetchrequest is being done. Here's how to do that: Add -com.apple.CoreData.SQLDebug 1 to the arguments passed at launch (under "Edit Scheme...")

0
votes

EDITED: This will get all albums in your store that wont have 0 Songs / tracks

NSFetchRequest *fetchRequestItems = [[NSFetchRequest alloc] init];
NSEntityDescription *entityList = [NSEntityDescription entityForName:@"Albums" inManagedObjectContext:managedObjectContext];
[fetchRequestItems setEntity:entityList];

[fetchRequestItems setPredicate:[NSPredicate predicateWithFormat:@"tracks.@count != 0 "]];

//Sort by last edit ordered
NSArray *sortDescriptors = [NSArray arrayWithObjects:nil];
[fetchRequestItems setSortDescriptors:sortDescriptors];

NSUInteger count = [managedObjectContext countForFetchRequest:fetchRequestItems error:nil];