Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CoreData: Fetch count of to-many relationship with NSDictionaryResultType

I have a big list of objects in Core Data (about 50 000 and periodically increasing). I fetch it with the following request:

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:[SongObject name]];
fetchRequest.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES]];
fetchRequest.propertiesToFetch = @[@"uid", @"name", @"toArtistRef.uid", @"toArtistRef.name"];
fetchRequest.resultType = NSDictionaryResultType;

Also entity SongObject contains relationship toSongsInPlaylistRef, which is to-many.

I need to fetch count of this set for each object. Due to big amount of data, I can't fetch the relationship itself. I tried adding @"toSongsInPlaylistRef.@count" and @"toSongsInPlaylistRef.count" but it crashes

Terminating app due to uncaught exception 'NSInvalidArgumentException', 
reason: 'Invalid to many relationship in setPropertiesToFetch: (toSongsInPlaylistRef.count)'

Please write any suggestions.

like image 895
hybridcattt Avatar asked Mar 23 '23 04:03

hybridcattt


2 Answers

To get the count of related object, you have to create a NSExpressionDescription and include that in the propertiesToFetch:

NSExpression *countExpression = [NSExpression expressionForFunction:@"count:"
        arguments:@[[NSExpression expressionForKeyPath:@"toSongsInPlaylistRef"]]];
NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];
[expressionDescription setName:@"playListCount"]; // Choose an appropriate name here!
[expressionDescription setExpression:countExpression];
[expressionDescription setExpressionResultType:NSInteger32AttributeType];

fetchRequest.propertiesToFetch = @[expressionDescription, ...];
like image 199
Martin R Avatar answered Apr 06 '23 10:04

Martin R


If you don't want to fetch all songs, but want to fetch their count number, maybe you should add a new property count, which will you increase as you add new song

like image 24
Anton Avatar answered Apr 06 '23 10:04

Anton