无法按块添加对象到数组实例

时间:2013-04-27 21:06:56

标签: iphone geolocation block instance-variables

我想将对象添加到NSMutableArray类型的实例var中,我在块中创建(reverseGeocodeLocation)。我可以在定义的对象中看到值。但我无法让它工作,将它们添加到实例var。

我已经考虑过__block或__strong前缀。但我似乎错过了一些东西。你能给我一个线索吗?在块中运行代码后,实例var“tableviewRows”仍为空。

谢谢! 塞巴斯蒂安

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {

    CLLocation *currentLocation = [locations lastObject];
    CLGeocoder *geoCoder = [[CLGeocoder alloc] init];

    [geoCoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {
        if (error == nil && [placemarks count] > 0) {
            CLPlacemark *placemark = [placemarks lastObject];
            CLLocation *userLocation = [placemark location];

            NSString *latitude = [NSString stringWithFormat:@"Lat. %f degrees", userLocation.coordinate.latitude];
            NSString *longitude = [NSString stringWithFormat:@"Long. %f degrees", userLocation.coordinate.longitude];
            NSString *altitude = [NSString stringWithFormat:@"Alt. %f m", userLocation.altitude];
            NSString *speed = [NSString stringWithFormat:@"Speed %f m/s", userLocation.speed];
            NSString *course = [NSString stringWithFormat:@"Course %f degrees", userLocation.course];

            [self.tableViewRows insertObject:latitude atIndex:0];
            [self.tableViewRows insertObject:longitude atIndex:1];
            [self.tableViewRows insertObject:altitude atIndex:2];
            [self.tableViewRows insertObject:speed atIndex:3];
            [self.tableViewRows insertObject:course atIndex:4];

        } else {
            NSLog(@"%@", error.debugDescription);
        }
    }];

    [self.tableView reloadData];
}

2 个答案:

答案 0 :(得分:0)

您必须在后台操作完成后重新加载表。所以它应该在完成处理程序中。

试试这个

__block NSArray *dataArray;

[geoCoder reverseGeocodeLocation:currentLocation 
               completionHandler:^(NSArray *placemarks, NSError *error) {
//...

   dataArray = @[latitude, longitude, altitude, speed, course];
   NSLog(@"Just checking... %@", dataArray);
   dispatch_sync(dispatch_get_main_queue(), ^{
      self.tableViewRows = [NSMutableArray arrayWithArray:dataArray];
      [self.tableView reloadData];
   });
 }];

答案 1 :(得分:0)

我刚调试了一些..但仍然是同样奇怪的事情......数组self.tableViewRows正在填充数据INSIDE块。但是当我在外面的数组上尝试“计数”时,返回的值是0.在块中它是5,应该是什么?!