如何按距离递增顺序对NSmutablearray进行排序?

时间:2013-02-02 09:59:10

标签: iphone ios ipad

我有一个朋友列表的朋友list.each有他们的lat& longs.I想要用他们距离autor的距离的上升速率对该数组进行排序。我发现了与autor的朋友的距离值,现在我想在距离的上升中对那个数组进行排序。这就是我这样做的方式,“

for(int i=0;i<[searchfriendarray count];i++)
        {
            NSDictionary *payload =[searchfriendarray objectAtIndex:i];
            NSLog(@"%@",payload);
             NSString *memberid = [payload objectForKey:@"userID"];
             CLLocation *locationofauthor;
            CLLocation *locationoffriends;
           if([memberid isEqualToString:uidstr])
            {

               NSString *latofauthor = [payload objectForKey:@"latitude"]; 
               NSString *longofauthor=[payload objectForKey:@"longitude"];
              double latofauthordouble = [latofauthor doubleValue];
             double longofauthordouble=[longofauthor doubleValue];;
            locationofauthor = [[CLLocation alloc] initWithLatitude:latofauthordouble  longitude:longofauthordouble];

            }
            else
            {
             NSString *latoffriends = [payload objectForKey:@"latitude"]; 
             NSString *longoffriends=[payload objectForKey:@"longitude"];
               double latoffriendsdouble = [latoffriends doubleValue];
                double longoffriendsdouble=[longoffriends doubleValue];;
               locationoffriends = [[CLLocation alloc] initWithLatitude:latoffriendsdouble  longitude:longoffriendsdouble];

              }
             CLLocationDistance distance = [locationofauthor distanceFromLocation:locationoffriends];

}

`任何人都可以帮助我按距离的升序排序我的阵列吗?

2 个答案:

答案 0 :(得分:2)

您可以在两个对象之间提供一组比较代码。然后,NSArray将根据需要对块进行多次调用来调用块。

NSArray sortedArray = [yourUnsortedArray sortedArrayUsingComparator:^NSComparisonResult(id         obj1, id obj2) {
       /*some code to compare obj1 to obj2. 
       for instance, compare the distances of obj1 to obj2.
       Then return an  NSComparisonResult 
       (NSOrderedAscending, NSOrderedSame, NSOrderedDescending);*/
    }];

P.S。要再次获取可变数组,只需在返回的对象上调用mutableCopy即可。

答案 1 :(得分:0)

NSSortDescriptor * descLastname = [[NSSortDescriptor alloc] initWithKey:@"active" ascending:YES];
[livevideoparsingarray sortUsingDescriptors:[NSArray arrayWithObjects:descLastname, nil]];
 [descLastname release];
videoparsing = [livevideoparsingarray copy];

livevideoparsingarray是我的排列和排序active是我的标签,它是在我排序的数组中。你随着你的要求改变了。