ios - 通过从解析数据计算的距离对 PFQueryTableViewController 单元格进行排序

标签 ios objective-c iphone uitableview parse-platform

我在解析时创建的数据库有问题。我有一张表格,显示了不同地方的里程数(一旦你从 DB 下载了列表),问题是我会订购它以获得向上的距离,但我不知道该怎么做。

- (void)viewDidLoad
{
    [super viewDidLoad];

    locationManager = [[CLLocationManager alloc] init];
    locationManager.delegate = self;
    locationManager.distanceFilter = kCLDistanceFilterNone;
    locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;

    if(IS_OS_8_OR_LATER) {

        [locationManager requestWhenInUseAuthorization];
        [locationManager requestAlwaysAuthorization];
    }

    [locationManager startUpdatingLocation];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(refreshTable:)
                                                 name:@"refreshTable"
                                               object:nil];
}

- (void)refreshTable:(NSNotification *) notification
{
    // Reload the recipes
    [self loadObjects];
}


- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"refreshTable" object:nil];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

- (PFQuery *)queryForTable
{
    PFQuery *query = [PFQuery queryWithClassName:self.parseClassName];

    query.limit = 100;

    [query orderByAscending:@"createdAt"];

    return query;   
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object
{
    static NSString *simpleTableIdentifier = @"RecipeCell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
    if (cell == nil) {

            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
    }

    NSString *AntDef = [NSString stringWithFormat:@"%@", [object objectForKey:@"AnteprimaDefault"]];

    if ([AntDef isEqualToString:@"Null"])
    {   
        PFImageView *thumbnailImageView = (PFImageView*)[cell viewWithTag:100];
        thumbnailImageView.image = [UIImage imageNamed:@"ImageDefault.png"];
        thumbnailImageView.layer.cornerRadius = thumbnailImageView.frame.size.width / 2;
        thumbnailImageView.clipsToBounds = YES;
        thumbnailImageView.layer.borderWidth = 0.5;
        thumbnailImageView.layer.borderColor = [UIColor lightGrayColor].CGColor;
    }

    else
    {   
        PFFile *thumbnail = [object objectForKey:@"Anteprima1"];
        PFImageView *thumbnailImageView = (PFImageView*)[cell viewWithTag:100];
        thumbnailImageView.image = [UIImage imageNamed:@"placeholder.jpg"];
        thumbnailImageView.file = thumbnail;
        thumbnailImageView.layer.cornerRadius = thumbnailImageView.frame.size.width / 2;
        thumbnailImageView.clipsToBounds = YES;
        [thumbnailImageView loadInBackground];
    }



    Lat = [[object objectForKey:@"Latitudine"] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    Long = [[object objectForKey:@"Longitudine"] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

    Latdouble = [Lat doubleValue];
    Longdouble = [Long doubleValue];


    NSArray *locations = [NSArray arrayWithObjects:[[CLLocation alloc] initWithLatitude:Latdouble longitude:Longdouble], nil];

    //NSLog(@"LOCATIONS COORDINATE: %@", locations);

    CLLocation *currentLocation = [[CLLocation alloc] initWithLatitude:locationManager.location.coordinate.latitude longitude:locationManager.location.coordinate.longitude];;
    CLLocation *nearestLoc = nil;
    CLLocationDistance nearestDis = FLT_MAX;

    for (CLLocation *location in locations) {
        CLLocationDistance distance = [currentLocation distanceFromLocation:location];

        for (CLLocation *location in locations) {
            distance = [currentLocation distanceFromLocation:location];
            if (nearestDis > distance) {
                nearestLoc = location;
                nearestDis = distance;
            }
        }

        text12 = [NSString  stringWithFormat:@"%.1f Km", nearestDis/1000];
    }

...
}

最佳答案

由于您使用的是 PFQueryTableViewController,因此无法调整加载的对象,因为 self.objects是只读的。您可以做的是制作一个副本,然后覆盖 - (PFUI_NULLABLE PFObject *)objectAtIndexPath:(PFUI_NULLABLE NSIndexPath *)indexPath方法以您想要的顺序返回对象。

最简单的排序方法是在加载完成后使用以下内容:

将属性添加到表单的 Controller :

// Property containing my sorted objects.
@property NSMutableArray *mySortedObjects;

然后在加载数据后的代码中,添加以下代码:
self.mySortedObjects=[self.objects mutableCopy];
[self.mySortedObjects sortUsingComparator:^NSComparisonResult(id a, id b) {
    NSLog(@"Sort a = %@",[a description]);
    NSLog(@"Sort b = %@",[b description]);
    NSComparisonResult result=NSOrderedSame;

    CLLocationDistance distanceFromA = <calculate distance>
    CLLocationDistance distanceFromB = <calculate distance>

    if (distanceFromA > distanceFromB){
      result=NSOrderedDescending;
    }
    else if (distanceFromA < distanceFromB){
        result=NSOrderedAscending;
    }
    else{
        result=NSOrderedSame;
    }

    return result;
}];

您现在拥有已加载对象的排序副本。

最后覆盖以下方法,以便更改为给定索引路径返回的对象:
- (PFUI_NULLABLE PFObject *)objectAtIndexPath:(PFUI_NULLABLE NSIndexPath *)indexPath{
  return self.mySortedObjects[indexPath.row];
  }

注意:这假定同一部分中的所有行。

关于ios - 通过从解析数据计算的距离对 PFQueryTableViewController 单元格进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29012609/

相关文章:

ios - 转换子图层时如何防止调用 layoutSubviews?

带有覆盖的 iOS 7 UIImagePickerController - 重拍和使用照片不可用

iphone - ARC 转换的应用程序问题 : passing adress of non local object to _autoreleaseing parameter for write-back

ios - 这个声明是什么意思?

objective-c - Objective-C "Bad URL"错误

iphone - 如何将 NSString 转换为数组?

iphone - 如何检测 NSURLConnection sendAsynchronousRequest 是否完成

ios - 在单元测试-Swift 中找不到模块 "MyApp"

ios - 如何使用 Xcode 10.2.1 创建通用库?

iphone - [self.navigationController popViewControllerAnimated :YES];? 之后调用什么方法