2011-06-10 51 views
0

我有一个位置获取代码,我想将它放入一个IBAction,但它有很多 - (VOID)。我如何使用相同的代码,但将其放入一个IBAction。将VOID代码转换为IBAction

这里是动作:

Ø

这是我希望把它的代码:

@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

你可能想在这个词是什么意思IBAction为你读了;它只是一个空洞花哨的名词,在这两种使用:

- (void)startUpdates; 

- (IBAction)buttonClick:(id)sender; 

表示“没有返回值或对象”。

我假设'放入IBAction'意味着有一个UI按钮或类似的元素触发一个位置获取并相应地更新UI。这不是直接可能的,因为位置是异步调用。你可以很容易地创建一个同步包装器,它将阻止所有其他操作,直到位置数据被返回,但是这是非常不鼓励的。相反,在处理位置时,通常更好地设计应用程序以向用户提供计算正在发生的指标(微调器/进度条),然后在位置回调返回时更新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; 
}