我有以下用于获取和分组搜索结果的代码:
NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Song"];
[request setPredicate:[NSCompoundPredicate andPredicateWithSubpredicates:predicates]];
[request setResultType:NSDictionaryResultType];
[request setSortDescriptors: @[[NSSortDescriptor sortDescriptorWithKey:@"timestamp" ascending:YES]]];
NSExpression *countExpression = [NSExpression expressionWithFormat:@"count:(SELF)"];
NSExpressionDescription *expressionDescriprion = [[NSExpressionDescription alloc] init];
[expressionDescriprion setName:@"count"];
[expressionDescriprion setExpression:countExpression];
[expressionDescriprion setExpressionResultType:NSInteger64AttributeType];
NSArray *properties = @[@"artistName", @"songName"];
[request setPropertiesToFetch:[properties arrayByAddingObject:expressionDescriprion]];
[request setPropertiesToGroupBy:properties];
self.fetchedItems = [self.managedObjectContext executeFetchRequest:request error:nil];
哪个非常好用,但是我遇到了问题,并且有点坚持,所以我需要使这个propertiesToGroupBy(属性类型是NSString *)不区分大小写。目前我有以下输出:
<_PFArray 0x7fa3e3ed0d90>(
{
artistName = "System of a Down";
count = 44;
songName = "Lonely Day";
},
{
artistName = "System Of A Down";
count = 2;
songName = "Lonely Day";
},
{
artistName = "System of a Down";
count = 4;
songName = "Chop Suey";
}
)
这是不正确的,所以我需要前两个项目在单个部分,因为这是同一个艺术家。
有没有办法实现这个目标?
答案 0 :(得分:0)
尝试使用NSExpressionDescription:
NSExpression *artistKeyPathExpression = [NSExpression expressionForKeyPath:@"artistName"];
NSExpression *artistExpression = [NSExpression expressionForFunction:@"uppercase:" arguments:@[artistKeyPathExpression]];
NSExpressionDescription *artistExpressionDescription = [NSExpressionDescription new];
artistExpressionDescription.name = @"groupByArtist";
artistExpressionDescription.expression = artistExpression;
artistExpressionDescription.expressionResultType = NSStringAttributeType;
NSExpression *songKeyPathExpression = [NSExpression expressionForKeyPath:@"songName"];
NSExpression *songExpression = [NSExpression expressionForFunction:@"uppercase:" arguments:@[songKeyPathExpression]];
NSExpressionDescription *songExpressionDescription = [NSExpressionDescription new];
songExpressionDescription.name = @"groupBySongName";
songExpressionDescription.expression = songExpression;
songExpressionDescription.expressionResultType = NSStringAttributeType;
[request setPropertiesToGroupBy:@[artistExpressionDescription, songExpressionDescription]];
请注意,我现在无法在XCode中检查此代码,因此可能包含印刷错误。对此感到抱歉,但我认为重点很明确。