拆分字典的NSMutableArray

问题描述 投票:-1回答:2

我正在尝试创建一个包含UITableView的视图,我想使用NSDictionaries的NSMutableArray填充UITableView。但是,我想使用其中一个NSDictionaries键值将NSMutableArray拆分为多个部分。

NSDictionary看起来像这样

First Name
Last Name
Age

NSMutableArray没有排序,但我想创建UITableView,它根据年龄分为几个部分,从最低到最高排序。

ios objective-c uitableview nsmutablearray nsdictionary
2个回答
1
投票

首先,您需要使用此函数对数组进行排序:

self.mutableArray = [mutableArray sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
    NSInteger ageA = [[(NSDictionary*)a objectForKey:@"Age"] integerValue];
    NSInteger ageB = [[(NSDictionary*)b objectForKey:@"Age"] integerValue];

   if(a < b) return NSOrderedAscending;
   if(b < a) return NSOrderedDescending;    

   return NSOrderedSame;
}];

现在,您可以从数组中提取键“Age”的不同值:

NSArray *uniqueAges = [_mutableArray valueForKeyPath:@"@distinctUnionOfObjects.Age"];

最后,您可以使用此数组返回tableView委托中的节数:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [uniqueAges count];
}

并且您还可以使用该数组返回该部分的名称:

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return [uniqueAges objectAtIndex:section];
    //remember to return a string if isn't so!
}

2
投票

NSArray有一个名为sortedArrayUsingComparator:的方法,它在NSArray对象上调用并获取一个块,该块以NSComparison结果作为参数返回。

您可以对Age键进行排序:

NSArray *sortedArray = [yourArray sortedArrayUsingComparator:
    ^NSComparisonResult(id a, id b) {
    NSInteger ageA = [[(NSDictionary*)a objectForKey:@"Age"] integerValue];
    NSInteger ageB = [[(NSDictionary*)b objectForKey:@"Age"] integerValue];

   if(a < b) 
       return NSOrderedAscending;
   if(b < a) 
       return NSOrderedDescending;
   else      
       return NSOrderedSame;
}];

为了拆分成部分,因为我们已经对它进行了排序,我们可以遍历数组:

NSMutableArray *sectionedArray = [NSMutableArray array];

for(NSDictionary *curDict in sortedArray) {
    if([[curDict objectForKey:@"Age"] isEqual:
        [[[sectionedArray lastObject] firstObject] objectForKey:@"Age"]) {
        [[sectionedArray lastObject] addObject:curDict];
    } else {
        NSMutableArray *newSection = [NSMutableArray arrayWithObject:curDict];
        [sectionedArray addObject:newSection];
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.