2

假设我将品牌名称存储在“品牌”属性中。如何按计数顺序获取它们?

例如,如果我有 5 个 Apple、3 个 Google、1 个 HP,它应该返回如下内容:

苹果

谷歌

生命值

4

1 回答 1

0

获取您的交易,然后

NSArray *unique =  
   [fetchedObjects valueForKeyPath:@"@uniqueUnionOfObjects.brand"]];

NSMutableArray *countsArray = [NSMutableArray arrayWithCapacity:unique.count];
for (NSString *brand in unique) { 
   NSArray *filtered = [fetchedObjects filteredArrayUsingPredicate:
     [NSPredicate predicateWithFormat:@"brand = %@", brand]];
   [countsArray addObject:@{@"brand":brand, @"count":@(filtered.count)}];
}

NSArray *result = [countsArray sortedArrayUsingSortDescriptors:
   @[[NSSortDescriptor sortDescriptorWithKey:@"count" ascending:NO]]]
于 2013-07-24T13:39:54.177 回答