CoreData:使用 NSDictionaryResultType 获取对多关系的计数 [英] CoreData: Fetch count of to-many relationship with NSDictionaryResultType

查看:14
本文介绍了CoreData:使用 NSDictionaryResultType 获取对多关系的计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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;

还有实体 SongObject 包含关系 toSongsInPlaylistRef,这是对多的.

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

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

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)'

请写下任何建议.

推荐答案

要获取相关对象的数量,您必须创建一个 NSExpressionDescription并将其包含在 propertiesToFetch 中:

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

这篇关于CoreData:使用 NSDictionaryResultType 获取对多关系的计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆