2013-02-14 114 views
0

这是我的一些代码。 一切正常。但不是排序。我想在“高度”后对我的数组进行排序 但它不起作用,所以这里是我的代码,我希望有人能帮助我。描述符后排序数组

 //Berechnung der Entfernung 
     erdradius = 6371; 

     //Koordinaten von Datenbank in String schreiben 
     NSString *latitude = [[news objectAtIndex:indexPath.row] objectForKey:@"Latitude"]; 
     NSString *longitude = [[news objectAtIndex:indexPath.row] objectForKey:@"Longitude"]; 

     entfernung = 0; 
     double lat1 = eigLat;     //eigener Standort Latitude 
     double long1 = eigLon;     //eigener Standort Longitude 
     double lat2 = [latitude doubleValue]; //Standort Heurigen Latitude 
     double long2 = [longitude doubleValue]; //Standort Heurigen Longitude 

     //Da man mit Bogenmaß rechnen muss! 
     double lat1rechnen = lat1*2*M_PI/360; 
     double long1rechnen = long1*2*M_PI/360; 
     double lat2rechnen = lat2*2*M_PI/360; 
     double long2rechnen = long2*2*M_PI/360; 

     //Formel zur Berechnung 
     entfernung = (erdradius * (2 * asin(sqrt(((sin(((lat1rechnen-lat2rechnen)/2)*(lat1rechnen-lat2rechnen)/2))+cos(lat1rechnen)*cos(lat2rechnen)*(sin(((long1rechnen-long2rechnen)/2)*(long1rechnen-long2rechnen)/2))))))); 

     //Werte in Strings damit man sie ausgeben kann 
     weg = [NSString stringWithFormat:@"%.2f km", entfernung]; 
     HeurigenName = [[news objectAtIndex:indexPath.row] objectForKey:@"Name"]; 


     newsMutable = [news mutableCopy]; 

     for (NSMutableDictionary* entry in newsMutable) 
     { 
      [entry setValue:[NSString stringWithFormat:weg] //[NSNumber numberWithDouble:entfernung] 
        forKey:@"Altitude"]; 
     } 


    NSLog(@"%@",newsMutable); 

     news = [newsMutable copy]; 

    NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"Altitude" ascending:YES]; 
    [news sortedArrayUsingDescriptors:[NSArray arrayWithObjects:descriptor, nil]]; 
    wegsorted = [news copy]; 


    //Ausgabe 
    cell.textLabel.text = [[news objectAtIndex:indexPath.row] objectForKey:@"Name"]; 
    cell.textLabel.textColor = [UIColor whiteColor]; 
    //cell.detailTextLabel.text =[[news objectAtIndex:indexPath.row] objectForKey:@"Altitude"]; 
    cell.detailTextLabel.text =[[news objectAtIndex:indexPath.row] objectForKey:@"Altitude"]; 

    return cell; 

有人能帮助我如何解决我的问题吗?

回答

2

sortedArrayUsingDescriptors返回一个新的排序数组,它不排序数组本身。 您可以使用

NSArray *sortedArray = [news sortedArrayUsingDescriptors:...]; 

得到一个新的有序数组,或者使用sortUsingDescriptors

[news sortUsingDescriptors:...] 

到(可变)阵列news自行解决。

另一个问题是,在for循环中,您为数组中的所有对象设置相同的“高度”值,因此按该键排序不会改变任何内容。

请注意newsMutable = [news mutableCopy]创建一个新的数组,但不复制数组中的元素,以便下面的for-loop修改news数组中的项。

+0

但是,当我在TableView中给出它时,数组中的每个对象都有另一个Altutude。但希望在这种高度之后进行分类。 – theandrew 2013-02-14 15:42:55

+0

@theandrew:我很难理解你的代码(即使我理解德语:-)。看起来这个代码是在'cellForRowAtIndexPath'中调用的,这是否正确? - 对'cellForRowAtIndexPath'中的表格视图排序不起作用。在显示表格视图之前,您应该只对数组排序一次,例如在'viewDidLoad'或'viewWillAppear'中。 – 2013-02-14 16:07:35

+0

好的谢谢:)我会测试它:) – theandrew 2013-02-14 16:08:52