【问题标题】:how to fetch most counted string value from core data如何从核心数据中获取最多计数的字符串值
【发布时间】:2013-07-24 10:21:12
【问题描述】:

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

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

苹果

谷歌

生命值

【问题讨论】:

  • Brand 是您的实体,name 是品牌名称的属性吗?
  • 品牌是我的属性。实体名称为 Transaction
  • 你的意思是它应该返回 9 条记录,即 5 条苹果记录,然后是 3 条谷歌记录 ecc ......还是只返回 3 条苹果、谷歌、惠普记录?
  • Apple、Google、Hp 订单中只有 3 条记录,因为 Apple 在数据库中的计数更高

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


【解决方案1】:

获取您的交易,然后

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]]]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-30
    相关资源
    最近更新 更多