我試圖在需要時獲取當前位置並立即停止更新位置。爲此,我編寫了下面的代碼,但持續等待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;
}
委託方法在啓動位置管理器的同一個線程中觸發,這意味着您使用'sleepForTimeInterval'來阻止它們。 –
我想到了這一點,但無論如何要解決這個問題嗎? – applefreak
常見的方法是在停止管理器後,移除'while(){sleep}'部分並將'//使用self.currentLocation'操作移動到從'locationManager:didUpdateToLocation:fromLocation:'調用的單獨方法中。這是代理人最自然的用法,您可以使用它。除此之外,還有很多其他解決方案,例如將觀察者添加到'locationUpdatedFlag' keypath或手動創建一個單獨的線程來等待它像你一樣睡覺。 –