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, ...];
如果您不想获取所有歌曲,但想要获取他们的计数,也许应该添加一个新的属性数量,这会随着添加新歌曲而增加
- mergeChangesFromContextDidSaveNotification之后的KVO通知
- '+ entityForName:nil不是合法的NSManagedObjectContext参数 – 核心数据
- 在应用上的许多用户之间共享核心数据
- 核心数据逆关系没有被设置
- 核心数据上下文和单身数据控制器
- executeFetchRequest抛出致命错误:NSArray元素无法匹配Swift数组元素types
- 将NSManagedObject的关系更改为不同的上下文
- 如何在轻量级核心数据迁移之后为现有实体的新属性设置默认值?
- 带两个NSFetchedResultsController实例的TableView