Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
635 views
in Technique[技术] by (71.8m points)

ios - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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, ...];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...