CoreData: Fetch count of to-many relationship with NSDictionaryResultType

前端 未结 2 1817
北海茫月
北海茫月 2020-12-18 08:41

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 = [         


        
相关标签:
2条回答
  • 2020-12-18 09:16

    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, ...];
    
    0 讨论(0)
  • 2020-12-18 09:19

    If you don't want to fetch all songs, but want to fetch their count number, maybe you should add a new property count, which will you increase as you add new song

    0 讨论(0)
提交回复
热议问题