我有一个看起来像这样的NSArray:
{"result":
[
{
"epoch":"1371333600"
},
{
"epoch":"1371420000"
},
{
"epoch":"1371333600"
}
]
}
我想对NSArray进行排序并创建一个新的,以便我可以更轻松地使用tableview方法来计算节和行。
所有相同的日期都需要在一个部分中。
数组应该如下面的示例,但我不知道如何到达那里。我尝试了NSPredicate并使用了一个循环,但它不起作用。
我想要的是什么:
{"result":
[
{"data":
[
{
"epoch":"1371333600"
},
{
"epoch":"1371333600"
}
]
},
{"data":
[
{
"epoch":"1371420000"
}
]
}
]
}
我的NSPredicate看起来像这样,但不会给我结果。
_finalArray = [[NSMutableArray alloc] init];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"epoch IN %@", [_resultArray valueForKey:@"epoch"]];
_predicateDate = [NSMutableArray arrayWithArray:[dataSortArray filteredArrayUsingPredicate:predicate]];
if ([_predicateDate count] != 0)
{
NSDictionary *itemsArrayDict = [NSDictionary dictionaryWithObject:_predicateDate forKey:@"data"];
[_finalArray addObject:itemsArrayDict];
}
答案 0 :(得分:3)
NSOrderedSet非常适合这种场合,因为它可以让你获得独特的字符串。
NSDictionary *dict1 = [NSDictionary dictionaryWithObject:@"2222222" forKey:@"epoch"];
NSDictionary *dict2 = [NSDictionary dictionaryWithObject:@"2222222" forKey:@"epoch"];
NSDictionary *dict3 = [NSDictionary dictionaryWithObject:@"1111111" forKey:@"epoch"];
NSArray *dictArray = @[dict1, dict2, dict3];
NSMutableArray *finalArray = [[NSMutableArray alloc]init];
NSArray *epoches = [dictArray valueForKey:@"epoch"];
NSOrderedSet *orderedSet = [NSOrderedSet orderedSetWithArray:epoches];
for (NSString *string in orderedSet) {
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"epoch == %@", string];
NSArray *resultsArray = [dictArray filteredArrayUsingPredicate:predicate];
[finalArray addObject:resultsArray];
}
答案 1 :(得分:0)
您好,您可以使用NSPredicate过滤数组,如:
//NSPredicate to filter an array
NSArray *data = [NSArray arrayWithObject:[NSMutableDictionary dictionaryWithObject:@"hello" forKey:@"Test"]];
NSArray *filtered = [data filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(Test == %@)", @"hello"]];
由于
答案 2 :(得分:0)
您似乎正在使用字典和数组。这就是我所取得的成就:
(result
(data
{
epoch = 1371333600;
},
{
epoch = 1371333600;
}
),
(data
{
epoch = 1371420000;
}
)
)
我没有使用谓词,但看起来它正在工作:)。这是代码:
// Initial input
NSArray *result = @[@{@"epoch":@"1371333600"},@{@"epoch":@"1371420000"},@{@"epoch":@"1371333600"}];
// Get unique values for the input
NSSet *resultSet = [NSSet setWithArray:result];
// Here we are going to store the final result
NSMutableArray *newResult = [[NSMutableArray alloc] init];
// Loop over the unique items
for (NSDictionary *uniqueItem in resultSet) {
// Here we are going to store the grouped data
NSMutableArray *dataResult = [[NSMutableArray alloc] init];
// Loop over the initial input
for (NSDictionary *resultItem in result) {
// Search for all the items that are equal to the uniqe
// I would rather include a count instead of repeating values :)
if([uniqueItem isEqual:resultItem]) {
[dataResult addObject:resultItem];
}
}
[newResult addObject:dataResult];
}
NSLog(@"%@", newResult);
干杯!