我有两个 nsmutablearrays,一个是距离数组,另一个是包含与这些距离相关联的图像的数组。我需要按升序对距离数组进行排序,然后根据它对图像数组进行排序。我试图用距离数组作为键来制作这两个数组的字典,但是当距离值相同时,在排序的图像数组中返回相同的图像。谁能帮我解决这个问题。 代码如下:
// Put the two arrays into a dictionary as keys and values
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:_locationImages forKeys:_distances];
// Sort the first array
NSArray *sortedFirstArray = [[dictionary allKeys] sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
if ([obj1 floatValue] > [obj2 floatValue])
return NSOrderedDescending;
else if ([obj1 floatValue] < [obj2 floatValue])
return NSOrderedAscending;
return NSOrderedSame;
}];
// Sort the second array based on the sorted first array
NSArray *sortedSecondArray = [dictionary objectsForKeys:sortedFirstArray notFoundMarker:[NSNull null]];
最佳答案
你不需要距离作为关键。只要有一系列字典。不知何故,这也让排序变得更容易。
NSMutableArray *dataArray = [NSMutableArray array];
for (int i=0; i<distanceArray.count; i++) {
[dataArray addObject:@{
@"distance" : distanceArray[i],
@"image" : imageArray[i]
}];
}
NSArray *sorted = [dataArray sortedArrayUsingDescriptors:@[
[NSSortDescriptor sortDescriptorWithKey:@"distance"
ascending:YES]]];
关于objective-c - 根据另一个距离数组对对象的 nsmutablearray 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14592764/