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

查看:252
本文介绍了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)'

请写任何建议。

Please write any suggestions.

推荐答案

要获取相关对象的计数,必须创建一个 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天全站免登陆