使用数组索引对数组进行排序

时间:2012-12-07 05:48:23

标签: iphone ios ios4 sorting

我被困在这里...... 我有两个数组Arr_title和Arr_distance 我使用此方法对Arr_distance进行了排序

NSSortDescriptor *sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"self" ascending:YES]autorelease];

sortedFloats = [appDel.Arr_distance sortedArrayUsingDescriptors:
                             [NSArray arrayWithObject:sortDescriptor]];

但问题是我想根据sortedFloats数组的索引对Arr_title进行排序......

提前帮助我..........

4 个答案:

答案 0 :(得分:1)

嘿,而不是采取两个不同的数组拿1个词典与 title,distance保存在数组中的字典然后排序该数组所以你有组合在一起,所以没有任何问题,由于任何类型的映射(按标题和距离)。

答案 1 :(得分:1)

试试这个,

NSDictionary *dict = [NSDictionary dictionaryWithObjects:Arr_title forKeys:Arr_distance];

NSSortDescriptor *sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"self" ascending:YES] autorelease];
sortedFloats = [appDel.Arr_distance sortedArrayUsingDescriptors:
                         [NSArray arrayWithObject:sortDescriptor]];


NSMutableArray *sortedTitles = [NSMutableArray array];

for (NSString *key in sortedFloats) {//or just use sortedTitles = [dict objectsForKeys:sortedFloats notFoundMarker:[NSNull null]];
    [sortedTitles addObject:[dict valueForKey:key]]; 
}

NSLog(@"%@",sortedValues);

sortedTitles应该按照与sortedFloats相同的顺序为您提供数组。

答案 2 :(得分:0)

如果我理解你的问题,你可以使用NSDictionary进行同样的任务

NSMutableArray *array = [NSMutableArray arrayWithArray:@[ @{@"title" : @"City1",@"dist" : @5},

                             @ {@"title" : @"City2",@"dist" : @2.3 },
                             @{@"title" : @"City3",@"dist" : @11.0 },
                             @{@"title" : @"City4",@"dist" : @1.0},
                             @{@"title" : @"City5",@"dist" : @.5},
                             @{@"title" : @"City6",@"dist" : @13 }]];

NSLog(@"dict<%@>",array);

NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"dist" ascending:YES];

NSArray *sortarray = [array sortedArrayUsingDescriptors:[NSArray arrayWithObject:sort]];

NSLog(@"sort array = <%@>",sortarray);

答案 3 :(得分:0)

我得到的解决方案见以下代码.........

NSSortDescriptor *sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"self" ascending:YES]autorelease];

sortedFloats = [appDel.Arr_distance sortedArrayUsingDescriptors:
                             [NSArray arrayWithObject:sortDescriptor]];

 NSLog(@" Sorted Array : %@", sortedFloats);

 NSDictionary *dictTitle = [NSDictionary dictionaryWithObjects:Arr_title   forKeys:appDel.Arr_distance];

// Sort the second array based on the sorted first array
sortedTitle = [dictTitle objectsForKeys:sortedFloats notFoundMarker:[NSNull null]];


NSLog(@" Sorted Title : %@",sortedTitle);


// Put the two arrays into a dictionary as keys and values
NSDictionary *dictAddress = [NSDictionary dictionaryWithObjects:Arr_address   forKeys:appDel.Arr_distance];

// Sort the second array based on the sorted first array
sortedAddress = [dictAddress objectsForKeys:sortedFloats notFoundMarker:[NSNull null]];


NSLog(@" Sorted Address : %@",sortedAddress);

如果在其他方法中使用,请不要忘记保留数组....