CoreData:使用NSDictionaryResultType提取多对多关系的计数

核心数据中有大量的对象(大约5万个,并且定期增加)。 我用下面的请求来获取它:

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关系,这是toSongsInPlaylistRef -many。

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

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

请写下任何build议。

要获取相关对象的计数,您必须创build一个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, ...]; 

如果您不想获取所有歌曲,但想要获取他们的计数,也许应该添加一个新的属性数量,这会随着添加新歌曲而增加