0

I am trying to get the current location whenever required and stop updating locations immediately. For this I wrote following code but continuos waiting on volatile flag doen't seem to working. It doesn't fire location updates evens when I am waiting on the flag. Could someone please tell me what's wrong in my code. Thanks.

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;
}
4

2 回答 2

0

你有那个委托回调是有原因的......所以你不必锁定线程轮询是否完成。改变你的类的设计,这样你就不会再这样做了。我敢打赌它会解决您的问题,并且您将获得更好的用户体验。

于 2012-08-31T11:22:41.377 回答
0

解决此问题的常用方法是删除while(){sleep}部件并将其移至停止管理器后// Use self.currentLocation operations调用的单独方法。locationManager:didUpdateToLocation:fromLocation:这是委托最自然的用法,您会想使用它。除此之外,还有许多其他解决方案,例如将观察者添加到locationUpdatedFlagkeypath 或手动创建separate线程以等待它像您一样休眠。

于 2012-09-02T09:40:54.040 回答