通过计算与解析数据的距离来订购PFQueryTableViewController单元格

时间:2015-03-12 14:35:07

标签: 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];
    }

...
}

1 个答案:

答案 0 :(得分:3)

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

最简单的排序方法是使用加载完成后跟随的内容:

向您的控制器添加一个属性:

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

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