iphone - 如何按距离升序对 NSmutablearray 进行排序?

标签 iphone ios ipad

我有一个 nsmutable 数组的 friend 列表。每个人都有他们的纬度和经度。我想用他们与 autor 的距离的升序对该数组进行排序。我发现了与 autor 的 friend 的距离值,现在我想要按照距离的升序对该数组进行排序。我就是这样做的,`

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];

}

`任何人都可以帮助我按照距离的升序对我的数组进行排序吗?

最佳答案

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

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);*/
    }];

附注要再次获取可变数组,只需对返回的对象调用 mutableCopy

关于iphone - 如何按距离升序对 NSmutablearray 进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14660714/

相关文章:

ipad - 仅针对 iPad 和 iPad 的 CSS 媒体查询?

ios - Nodejs Socket.io 适用于桌面 safari 和 chrome,但不适用于 iPhone

ios - NSBundle实例方法URLForResource :withExtension returning invalid CFStringRef on device

ios - 检查 NSArray 是否排序

css - -webkit-text-size-调整在 iPad OS 13 上不起作用

ios - 仅横向 iOS 应用程序无法正确显示(与 shouldAutorotateToInterfaceOrientation 无关)

ios - 使用自定义帧图像执行自定义动画

iphone - 数组与对象 : Objects should be NSStrings

javascript - 我可以在 iPhone 上运行 javascript 运行时(如 v8)吗?

ios - 在 iPad 中加载 PDF