【发布时间】:2012-04-12 22:11:19
【问题描述】:
如何使用以下方法对数组进行排序并保留重复项?我想要的只是对距离数组进行排序,并让 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];
}
}
}
【问题讨论】:
-
dictionary中有什么内容? -
Inafziger,我添加了更多代码
-
你指的是什么方法?
sortedArrayUsingSelector:? -
是的,sortedArrayUsingSelector:@selector(compare:) 在对它们进行排序时取出重复项。这弄乱了我的索引
-
将
NSLog(@"DICTIONARY BEFORE %@", dictionary);添加到您的程序并发布结果。
标签: ios arrays sorting duplicates nsdictionary