2011-06-10 55 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; 
}