如何在Objective C中组合数组字典中的两个键值

问题描述 投票:0回答:1

我在数组中拥有字典的多个对象。现在,特别是字典我从另一个键有两个键“category”和“createdDate”。

情况: - 我需要一个具有对象的数组,使得具有相同日期的类别可以被聚合在一起形成一个对象。那些具有不同日期的类别是它自己的另一个对象。

在我的脑海中,我必须在键之间放置各种比较条件,这是实现它的基本方法。 ---不需要

需要您对不同方法的宝贵建议,这是必需的,也不复杂。提前致谢。

objective-c
1个回答
0
投票

在这里,你举个例子

NSDateFormatter * df = [NSDateFormatter new];
for (id object in self.mainArray) {
    [df setDateFormat:@"MM/dd/yyyy"];
    NSString *dateString = [df stringFromDate:[object objectForKey:@"createdDate"]];
    NSMutableArray *sectionArray = self.totalsSectionDictionary[dateString];
    if (!sectionArray) {
        sectionArray = [NSMutableArray array];
        self.totalsSectionDictionary[dateString] = sectionArray;
    }
    NSString * tempString = [object valueForKey:@"category"]
    [sectionArray addObject:@{@"value" : tempString}];
}

这会导致按日期组合的对象字典作为字符串值,并且每个日期键内部都存在该日期的值数组。从那里,您需要梳理出这些值并对其进行排序:

NSArray * tempUnsortedArray = [self.totalsSectionDictionary allKeys];
NSArray *arrKeys = [tempUnsortedArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"MM/dd/yyyy"];
    NSDate *d1 = [df dateFromString:(NSString*) obj1];
    NSDate *d2 = [df dateFromString:(NSString*) obj2];
    return [d2 compare: d1];
}];
NSMutableArray * tempArray1 = [NSMutableArray array];
for (NSInteger i = 0; i < arrKeys.count; i++) {
    NSMutableArray *sectionArray = self.totalsSectionDictionary[arrKeys[i]];
}

你去了,最后一个for循环将允许你按日期迭代存储在原始字典中的每个section数组,这样你就可以把它们放到一个集合或表视图中

祝好运

© www.soinside.com 2019 - 2024. All rights reserved.