2012-08-31 26 views
0

我試圖在需要時獲取當前位置並立即停止更新位置。爲此,我編寫了下面的代碼,但持續等待volatile標誌似乎不起作用。當我在國旗上等待時,它不會觸發位置更新。有人可以告訴我我的代碼中有什麼問題。謝謝。iOS:繼續等待旗幟直到位置更新

CurrentLocation.h file: 

@property (nonatomic, assign) volatile BOOL locationUpdatedFlag; 
@property (nonatomic, strong) CLLocationManager *locationManager; 
@property (nonatomic, strong) CLLocation *currentLocation; 

CurrentLocation.m file: 

@synthesize currentLocation = _currentLocation; 
@synthesize locationManager = _locationManager; 
@synthesize locationUpdatedFlag = _locationUpdatedFlag; 

- (void)xxx 
{ 
    self.locationManager = [[CLLocationManager alloc] init]; 
    self.locationManager.delegate = self; 
    self.locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters; 
    [self.locationManager startUpdatingLocation]; 

    self.locationUpdatedFlag = NO; 

    while(!self.locationUpdatedFlag) 
     [NSThread sleepForTimeInterval:.1]; 

    // Use self.currentLocation 

} 

#pragma mark - CLLocationManagerDelegate 

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation 
{ 
    self.currentLocation = newLocation; 
    self.locationUpdatedFlag = YES; 
    [manager stopUpdatingLocation]; 
} 

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error 
{ 
    NSLog(@"Error from Location Manager"); 
    self.locationUpdatedFlag = YES; 
} 
+1

委託方法在啓動位置管理器的同一個線程中觸發,這意味着您使用'sleepForTimeInterval'來阻止它們。 –

+0

我想到了這一點,但無論如何要解決這個問題嗎? – applefreak

+0

常見的方法是在停止管理器後,移除'while(){sleep}'部分並將'//使用self.currentLocation'操作移動到從'locationManager:didUpdateToLocation:fromLocation:'調用的單獨方法中。這是代理人最自然的用法,您可以使用它。除此之外,還有很多其他解決方案,例如將觀察者添加到'locationUpdatedFlag' keypath或手動創建一個單獨的線程來等待它像你一樣睡覺。 –

回答

0

修復此問題的常用方法是在停止管理器後,刪除while(){sleep}零件並將// Use self.currentLocation operations移動到單獨的方法中,調用方式爲locationManager:didUpdateToLocation:fromLocation:。這是代理人最自然的用法,您可以使用它。除此之外,還有很多其他解決方案,例如將觀察者添加到locationUpdatedFlag keypath或手動創建separate線程以等待它像您一樣睡覺。

0

你有這個委託回調的原因......所以你不必鎖定線程輪詢,如果有事情完成。改變你班級的設計,讓你不再那樣做。我敢打賭,它會解決你的問題,你會有更好的用戶體驗。