2012-09-16 33 views
0

的一部分分揀陣列I具有點在地圖上的陣列。 我正確填充數組,然後在地圖上爲它們製作註釋。一切工作正常。 我有另一個tableview與相同的數組,並在單元格的「副標題」中,我計算到用戶和現在的距離。一切工作正常。的UITableView IOS:基於計算出的距離不是數組

現在,我想在排序表視圖列表,換句話說,我希望通過距離相同的數組進行排序,最低到最高。

的事情是,該距離不在陣列的一部分。所以我如何交叉匹配數組的距離,以便當我排序距離時,它將它的屬性對象放在數組中,並對數組進行排序?

我是相當新的IOS,但我已成功地釋放,現在3級的應用程序,而這一次是第四,要複雜得多,我想我已經覆蓋了相當不錯的地上,使應用程序爲止。從mapview到使用搜索控制器的tableview和一切。我只是缺少排序。

我想象我需要一些標籤或屬性添加到每個對象的陣列中,並將其分配到的距離陣列中的每個的距離。 任何建議,將不勝感激:) 在此先感謝。

回答

3
// Assuming you have your points on the map in an NSArray called 
// pointsOnMapArray and your distances in distanceArray, create a 
// new mutable array to hold both. Note, the "distances" in this 
// case are stored as NSStrings. We'll want to convert them to 
// doubles before sorting them. 
NSMutableArray *newArray = [[NSMutableArray alloc] init]; 

// Iterate over all of the points, and add a new element to the mutable 
// array which is a new array containing a point and its distance. The 
// distance is converted from an NSString to an NSNumber containing a 
// doubleValue. 
int i; 
for (i = 0; i < pointsOnMapArray.count; i++) { 
    NSArray *newItem = [NSArray arrayWithObjects: [pointsOnMapArray objectAtIndex: i], [NSNumber numberWithDouble:[[distanceArray objectAtIndex: i] doubleValue]], nil]; 
    [newArray addObject: newItem]; 
} 

// Now, sort the new array based upon the distance in the second element 
// of each array (ie, the distance). 
[newArray sortUsingComparator: ^(id obj1, id obj2) { 
    NSNumber *dist1 = [obj1 objectAtIndex:1]; 
    NSNumber *dist2 = [obj2 objectAtIndex:1]; 

    return [dist1 compare:dist2]; 
}]; 
+0

這一個工作可愛。但實際的比較很奇怪。它正在考慮256655.030734小於4947.431243,這不應該是這樣嗎? –

+0

您的距離NSNumbers是否包含浮標? – vacawama

+0

他們是NSStrings。它就像只是比較第一位數字。我會盡量讓他們成爲nsnumbers。 2分鐘。 –

1

嘗試使與距離和數組的元素的字典。然後通過排序距離,可以對數組元素進行相應的排序。

NSMutableDictionary *dict=[[NSMutableDictionary alloc]init]; 
[dict setObject:(array element) forKey:(correspondingDistance)]; 

現在通過對鍵進行排序,您可以相應地對數組元素進行排序。

+0

我會試試這個也回到你身邊:)謝謝你的回覆我不知道爲什麼我沒有想到這個:) –