【问题标题】:CoreData: Fetch count of to-many relationship with NSDictionaryResultTypeCoreData:获取与 NSDictionaryResultType 的一对多关系的计数
【发布时间】:2013-10-10 04:49:31
【问题描述】:

我在 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,它是对多的。

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

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

请写出任何建议。

【问题讨论】:

    标签: ios objective-c core-data


    【解决方案1】:

    如果您不想获取所有歌曲,但想获取它们的计数,也许您应该添加一个新的属性计数,当您添加新歌曲时会增加

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 就在几个小时前,我有机会回到这个问题并尝试您的建议。它完美地工作。谢谢!
      • @hybridcattt:不客气,我很高兴它对你有用!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-08
      • 1970-01-01
      • 1970-01-01
      • 2014-07-19
      • 1970-01-01
      相关资源
      最近更新 更多