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.
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, ...];
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With