我正在使用以下代码来检索一些数据,但是问题是每次我运行应用程序时,我都以不同的顺序接收数据:

[PFGeoPoint geoPointForCurrentLocationInBackground:^(PFGeoPoint *geoPoint, NSError *error) {

    if (!error) {

        NSDate *currentDate = [NSDate date];

        __block PFQuery *query = [[PFQuery alloc] initWithClassName:@"orders"];

        [query setLimit:25];

        [query whereKey:@"location" nearGeoPoint:geoPoint withinKilometers:kilometers];
        [query whereKey:@"createdAt" lessThanOrEqualTo:currentDate];

        [query orderByDescending:@"createdAt"];

        [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
            if (objects.count > 0) {

                [self.flebData removeAllObjects];
                [self.flebData addObjectsFromArray:objects];

                dispatch_async(dispatch_get_main_queue(), ^{

                    [self.tableView reloadData];

                    [self.tableView.pullToRefreshView stopAnimating];
                    // once refresh, allow the infinite scroll again
                    self.tableView.showsInfiniteScrolling = YES;

                });
            }
            query = nil;
        }];
    }
}];


这是错误还是我的代码有问题?

最佳答案

根据PFQuery docs,大多数位置约束,特别是whereKey:nearGeoPoint:whereKey:nearGeoPoint:withinMiles:whereKey:nearGeoPoint:withinKilometers:whereKey:nearGeoPoint:withinRadians:,强制查询返回结果“按距参考点的距离(最近到最远)排序”;因此,如果您的位置完全改变,结果顺序也会改变。

但是位置约束whereKey:withinGeoBoxFromSouthwest:toNortheast:不会对结果强加任何距离排序算法。因此,正如Paulw11在其评论中链接的答案所指出的那样,您可以将该方法与[query orderByDescending:@"createdAt"];一起使用,以获得所需的结果顺序。

但是,对您来说潜在的问题是whereKey:withinGeoBoxFromSouthwest:toNortheast:方法在正方形内检查,whereKey:nearGeoPoint:withinKilometers:在圆半径内检查,并且它们通常是不同的方法。

因此,如果在您的圆公里半径内查找点并对结果按照创建顺序进行排序对您来说很重要,那么也许在查询中找到results后,应该对它们进行排序,例如:

PFQuery *query = [[PFQuery alloc] initWithClassName:@"orders"];

[query setLimit:25];

[query whereKey:@"location" nearGeoPoint:geoPoint withinKilometers:kilometers];
[query whereKey:@"createdAt" lessThanOrEqualTo:currentDate];

[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {

    if (objects.count > 0) {

        createdAtDescriptor = [[NSSortDescriptor alloc] initWithKey:@"createdAt" ascending:NO];
        sortDescriptor = [NSArray arrayWithObject:createdAtDescriptor];
        self.flebData = [objects sortedArrayUsingDescriptors:sortDescriptor];

07-27 14:39