gpt4 book ai didi

ios - 如何防止sortedArrayUsingSelector删除重复条目(ios)?

转载 作者:行者123 更新时间:2023-12-01 18:30:02 24 4
gpt4 key购买 nike

如何使用以下方法对数组进行排序,并保留重复项?我想要的只是对distance数组进行排序,并按相同顺序对lineItems数组进行排序,以便我的订单项按距离进行排序。是否有捷径可寻?我已经尝试了很多不同的实现,但是没有运气。

lineItems = [[NSMutableArray alloc] initWithArray:(NSMutableArray *)[data objectForKey:@"line_items"]];
distanceArray = [[NSMutableArray alloc] initWithCapacity:[lineItems count]];
for (int i = 0; i < [lineItems count]; i++) {
CLLocation *spotLocation = [[CLLocation alloc] initWithLatitude:[[[lineItems objectAtIndex:i] objectForKey:@"latitude"] floatValue] longitude:[[[lineItems objectAtIndex:i] objectForKey:@"longitude"] floatValue]];
CLLocationDistance distance = ([myLocation distanceFromLocation:spotLocation] / 1000) * 0.621371192;
NSNumber *foo = [[NSNumber alloc] initWithDouble:distance];
[distanceArray insertObject:foo atIndex:i];
}

我的气泡排序实现:
for (int i=0;i<[distanceArray count]-1;i++){
for(int j=1;j<[distanceArray count];j++){
if ([[distanceArray objectAtIndex:i]doubleValue] >[[distanceArray objectAtIndex:j]doubleValue]){
NSNumber *temp_i = [[NSNumber alloc] initWithDouble:[[distanceArray objectAtIndex:i]doubleValue]];
NSNumber *temp_j = [[NSNumber alloc] initWithDouble:[[distanceArray objectAtIndex:j]doubleValue]];
[distanceArray removeObjectAtIndex:i];
[distanceArray removeObjectAtIndex:j];
[distanceArray insertObject:temp_j atIndex:i];
[distanceArray insertObject:temp_i atIndex:j];

NSDictionary *tempObj_i = [[NSDictionary alloc] initWithDictionary:[lineItems objectAtIndex:i]];
NSDictionary *tempObj_j = [[NSDictionary alloc] initWithDictionary:[lineItems objectAtIndex:j]];
[lineItems removeObjectAtIndex:i];
[lineItems removeObjectAtIndex:j];
[lineItems insertObject:tempObj_j atIndex:i];
[lineItems insertObject:tempObj_i atIndex:j];
}
}
}

最佳答案

您的问题不是-sortedArrayUsingSelector:,而是NSDictionary-allKeys方法。键在字典中是唯一的,因此-allKeys数组不会有任何重复项。

使用单独的NSArray实例存储排序结果,或使用inafziger的建议。

关于ios - 如何防止sortedArrayUsingSelector删除重复条目(ios)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10132627/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com