如何从核心数据中获取大部分计数的字符串值

时间:2013-07-24 10:21:13

标签: ios objective-c database core-data fetch

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

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

苹果

谷歌

HP

1 个答案:

答案 0 :(得分: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]]]