2016-05-05 4 views
0

私はObjective-Cについて初心者です。専門家が私を助けてくれることを願っています。 JSONエンコーディングで名前と住所を返すWebサービスがあります。私のアプリ側では、サブタイトルスタイルのセルを持つUITableViewがあります。私は主ラベルの名前と現在のデバイスの位置からのアドレスの距離を2番目のラベルに表示しています。私は距離上でUITableViewCellを並べ替える必要があります。私は名前と距離を表示することができますが、距離をソートする方法はわかりません。助けていただければ幸いです。UITableViewCellソート

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

    static NSString *CellIdentifier = @"Cell"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]; 

    if (cell == nil){ 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]; 
    } 

    NSDictionary *info = [json objectAtIndex:indexPath.row]; 

    NSString *sName = [info objectForKey:@"Name"]; 
    NSString *sAddress = [info objectForKey:@"Address"]; 

    cell.textLabel.text = sName; 

    CLGeocoder *geocoder = [[CLGeocoder alloc] init]; 
    [geocoder geocodeAddressString:sAddress completionHandler:^(NSArray *placemarks, NSError *error) { 
     if (error){ 
      NSLog(@"%@", error); 
     } else { 
      CLPlacemark *placemark = [placemarks lastObject]; 

      CLLocation *restLocation = [[CLLocation alloc] initWithLatitude:placemark.location.coordinate.latitude longitude:placemark.location.coordinate.longitude]; 

      CLLocation *userLocation = [[CLLocation alloc] initWithLatitude:self.locationManager.location.coordinate.latitude longitude:self.locationManager.location.coordinate.longitude]; 

      CLLocationDistance distance = [userLocation distanceFromLocation:restLocation]; 
      distance = distance/1000; 

      NSString *sDistance = [NSString stringWithFormat: @"%@%1.2f%@",@"Distance: ",distance, @" km"]; 

      cell.detailTextLabel.text = sDistance; 
     } 

    }]; 

    return cell; 
} 
+3

実際にセルをソートしません。テーブルビューを作成するために使用するデータをソートする必要があります。テーブルビューを読み込む前にこれを行います。その後、セルはデータと同じ順序で表示されます。 – rmaddy

答えて

0

おかげrmaddyとスティーブンcellForRowAtIndexPathデリゲートの前に少し変更。

私はgeoCodeFromStringを動作させることができませんでした。そのため、Google APIを使用してアドレスの座標を取得しました。 NSSortDescriptorを使用して距離キーを追加し、この新しい配列をソートするために、json配列のアドレスを変更しています。

1

ソート・データ・ソースの代わりに、セル、

json = [json sortedArrayUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) { 
    NSString *address1 = [obj1 objectForKey:@"Address"]; 
    NSString *address2 = [obj2 objectForKey:@"Address"]; 
    return [self distanceFromAddress:address1] > [self distanceFromAddress:address2]; 
}]; 

- (CLLocationDistance)distanceFromAddress: (NSString *)sAddress { 

//Put your Geocoder method here 

}