将VOID代码转换为IBAction

时间:2011-06-10 19:33:59

标签: iphone ios xcode ios4

我有一个位置getter代码,我想将它放入IBAction,但它有很多   - (VOID)在里面。我如何使用相同的代码,但将其放入一个IBAction。

以下是行动:

0

以下是我想要输入的代码:

 @synthesize locationManager, delegate;

    BOOL didUpdate = NO;

    - (void)startUpdates
    {
    NSLog(@"Starting Location Updates");

    if (locationManager == nil)
        locationManager = [[CLLocationManager alloc] init];

    locationManager.delegate = self;

    // You have some options here, though higher accuracy takes longer to resolve.
    locationManager.desiredAccuracy = kCLLocationAccuracyKilometer;  
    [locationManager startUpdatingLocation];    
    }



    - (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
    {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Your location could not be determined." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
    [alert show];
    [alert release];      
    }

    // Delegate method from the CLLocationManagerDelegate protocol.
    - (void)locationManager:(CLLocationManager *)manage didUpdateToLocation:(CLLocation     *)newLocation fromLocation:(CLLocation *)oldLocation
    {
    if (didUpdate)
        return;

    didUpdate = YES;

    // Disable future updates to save power.
    [locationManager stopUpdatingLocation];

    // let our delegate know we're done
    [delegate newPhysicalLocation:newLocation];
    }

    - (void)dealloc
    {
    [locationManager release];

    [super dealloc];
    }

    @end

1 个答案:

答案 0 :(得分:1)

您可能想要了解IBAction的含义;它只是虚空的一个奇特术语,用于两者:

- (void)startUpdates;

- (IBAction)buttonClick:(id)sender;

表示'不返回任何值或对象'。

我假设通过'放入IBAction',您的意思是让UI按钮或类似元素触发对位置的提取并相应地更新UI。这不是直接可能的,因为location是异步调用。您可以轻松创建一个同步包装器,它将阻止所有其他操作,直到返回位置数据,但强烈建议不要这样做。相反,在处理位置时,通常最好设计应用程序以向用户提供计算正在发生的指示(微调器/进度条),然后在位置回调返回时更新UI。

这可能看起来像这样:

- (IBAction)locationButtonClick:(id)sender {
  self.spinner.hidden = NO;
  [self.spinner startAnimating];

  self.myLocationManager.delegate = self;
  [self.myLocationManager startUpdates];
}

- (void)newPhysicalLocation:(id)newLocation {
   //TODO: Update UI
   [self.spinner stopAnimating];
   self.spinner.hidden = YES;
}