如何按目标C中的数组元素进行分组

时间:2016-08-22 08:59:32

标签: ios objective-c nsarray nsdictionary

如上所述,可以使用swift to How to group by a array:How to group by the elements of an array in Swift使用此扩展名:

public extension SequenceType {

  /// Categorises elements of self into a dictionary, with the keys given by keyFunc

  func categorise<U : Hashable>(@noescape keyFunc: Generator.Element -> U) -> [U:[Generator.Element]] {
    var dict: [U:[Generator.Element]] = [:]
    for el in self {
      let key = keyFunc(el)
      if case nil = dict[key]?.append(el) { dict[key] = [el] }
    }
    return dict
  }
}

如何对Objective C进行相同的操作

1 个答案:

答案 0 :(得分:1)

目标C中的结果相同。我尝试了这个问题,现在我得到了解决方案。它工作正常。

NSArray *array = @[@{@"name" : @"lunch", @"date" : @"01-01-2015" , @"hours" : @"1"},
                   @{@"name" : @"dinner", @"date" : @"01-01-2015" , @"hours" : @"1"},
                   @{@"name" : @"dinner", @"date" : @"01-01-2015" , @"hours" : @"1"},
                   @{@"name" : @"lunch", @"date" : @"01-01-2015" , @"hours" : @"1"},
                   @{@"name" : @"dinner", @"date" : @"01-01-2015" , @"hours" : @"1"},
                   ];

NSMutableArray *resultLunchArray = [NSMutableArray new];
NSMutableArray *resultDinnerArray = [NSMutableArray new];
NSMutableArray *finalResultsArray = [NSMutableArray new];
NSArray *groupLunch = [array valueForKeyPath:@"@distinctUnionOfObjects.name"];
for (NSString *str in groupLunch)
{
    NSArray *groupNames = [array filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"name = %@", str]];
    if([str isEqualToString:@"lunch"])
    {
      for (int i = 0; i < groupNames.count; i++)
      {
         NSString *nameLunch = [[groupNames objectAtIndex:i] objectForKey:@"name"];
         NSString *dateLunch = [[groupNames objectAtIndex:i] objectForKey:@"date"];
         NSString *strNameLunch = [NSString stringWithFormat:@"%@ : %@",nameLunch,dateLunch];
         [resultLunchArray addObject:strNameLunch];
       }
        [finalResultsArray addObject:resultLunchArray];
    }
    else{
        for (int i = 0; i < groupNames.count; i++)
        {
            NSString *nameDinner = [[groupNames objectAtIndex:i] objectForKey:@"name"];
            NSString *dateDinner = [[groupNames objectAtIndex:i] objectForKey:@"date"];
            NSString *strNameDinner = [NSString stringWithFormat:@"%@ : %@",nameDinner,dateDinner];
            [resultDinnerArray addObject:strNameDinner];
        }
        [finalResultsArray addObject:resultDinnerArray];
    }
}
NSLog(@"The final results are - %@",finalResultsArray);

输出结果是

 The final results are - (
    (
    "lunch : 01-01-2015",
    "lunch : 01-01-2015"
),
    (
    "dinner : 01-01-2015",
    "dinner : 01-01-2015",
    "dinner : 01-01-2015"
)
)