![](/img/trans.png)
[英]CoreData fetch with NSSortDescriptor by count of to-many relationship
[英]CoreData: Fetch count of to-many relationship with NSDictionaryResultType
我在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;
實體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)'
請寫下任何建議。
要獲取相關對象的計數,您必須創建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, ...];
如果你不想獲取所有歌曲,但想要獲取他們的計數,也許你應該添加一個新的屬性計數,當你添加新歌時你會增加
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.