CoreData:获取与NSDictionaryResultType的多对多关系的计数

hyb*_*ttt 3 core-data objective-c ios

我在Core Data中有一个很大的对象列表(大约50 000并且会定期增加).我用以下请求获取它:

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;
Run Code Online (Sandbox Code Playgroud)

实体SongObject也包含关系toSongsInPlaylistRef,它是to-many.

我需要为每个对象获取此set的计数.由于数据量很大,我无法获取关系本身.我尝试添加 @"toSongsInPlaylistRef.@count",@"toSongsInPlaylistRef.count" 但它崩溃了

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

请写下任何建议.

Mar*_*n R 5

要获取相关对象的计数,您必须创建一个NSExpressionDescription 并包含在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, ...];
Run Code Online (Sandbox Code Playgroud)