Reputation: 3299
In my app, I have a dictionary with two array like:
NSDictionary *d=[[NSDictionary alloc]initWithObjectsAndKeys:listOfEvents,@"l",arr_distance,@"d", nil];
NSLog(@"%@",d);
d = (
"353.90",
"354.68",
"350.42",
"1.18"
);
l = (
{
Contestant1 = "Jon jones";
Contestant2 = "Anderson silva";
},
{
Contestant1 = "Jon jones";
Contestant2 = "Anderson silva";
},
{
Contestant1 = "Jon jones";
Contestant2 = "Anderson silva";
},
{
Contestant1 = "Jon jones";
Contestant2 = "Anderson silva";
}
);
}
I want to sort the dictionary with first array and when the index changes , the second array index also changed according to it.
Both arrays index are related to each other.
@ABC your tried code
NSDictionary *dict = [NSDictionary dictionaryWithObjects:listOfEvents forKeys:arr_distance];
NSArray *sortedArray = [arr_distance sortedArrayUsingSelector:@selector(compare:)];
NSMutableArray *sortedValues = [NSMutableArray array];
for (NSString *key in sortedArray) {
[sortedValues addObject:[dict valueForKey:key]];
}
NSLog(@"%@",sortedValues);
Result:
{ 1.18,2563.91,2563.41,2563.39,350,353,354}
Upvotes: 2
Views: 120
Reputation: 23278
Here is one way to do it,
NSArray *a = [NSArray arrayWithObjects:@"8", @"2", @"4", nil];
NSArray *b = [NSArray arrayWithObjects:@"val1", @"val2", @"val3", nil];//This can be an array of any objects
or
a = ["353.90", "354.68", "350.42", "1.18"];
b = [{
Contestant1 = "Jon jones";
Contestant2 = "Anderson silva";
},
{
Contestant1 = "Jon jones";
Contestant2 = "Anderson silva";
},
{
Contestant1 = "Jon jones";
Contestant2 = "Anderson silva";
},
{
Contestant1 = "Jon jones";
Contestant2 = "Anderson silva";
}];
Do it like this,
NSDictionary *dict = [NSDictionary dictionaryWithObjects:b forKeys:a];
NSArray *sortedArray = [a sortedArrayUsingComparator:^(id firstObject, id secondObject) {
return [((NSString *)firstObject) compare:((NSString *)secondObject) options:NSNumericSearch];
}];
NSMutableArray *sortedValues = [NSMutableArray array];
for (NSString *key in sortedArray) {
[sortedValues addObject:[dict valueForKey:key]];
}
NSLog(@"%@",sortedValues);
Upvotes: 1