2016-11-17 77 views
0

下面是我的一些代码片段CLLocationManager stopUpdatingLocation不会停止

BOOL checkingForLocation; 
. 
. 
. 
- (IBAction)LocationButtonTapped:(id)sender { 
    [locationManager startUpdatingLocation]; 
    checkingForLocation = YES; 
} 
. 
. 
. 
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations { 

    [locationManager stopUpdatingLocation]; 
    // locationManager = nil; 


    if (checkingForLocation) { 
     checkingForLocation = NO; 
     NSLog(@"here"); 
     // fetch data from server using location and present view controllers 
    } 
} 

didUpdateLocations被多次调用,因为是的LocationManager持续更新每startUpdatingLocation位置。我的应用程序有一个错误,if(checkingForLocation)中的代码多次运行并多次呈现视图导致不期望的结果。

1)为什么stopUpdatingLocation不会停止对didUpdateLocations的进一步调用?

2)此外,如果checkingForLocation已经被设置为NO为什么到didUpdateLocations随后调用还是把checkingForLocationYES。那里有种族条件吗?

通过搜索其他SO问题,我发现设置locationManager = nil将停止对didUpdateLocations的额外调用,它确实解决了我的情况中的问题,但没有真正的解释。看来,stopUpdatingLocation应该照顾到这一点。任何见解都非常感谢。

谢谢

+0

你在哪里调用'[locationManager startUpdatingLocation]; checkingForLocation = YES;'? – OgreSwamp

+0

@OgreSwamp我在按下按钮时调用它。为了清楚起见,我添加了上面的IBAction方法。 – galenom

回答

0

didUpdateLocations:可以频繁地调用而由于其异步性质和optimisations的任何时间:

因为它可能需要几秒钟返回初始位置时, 位置经理通常会立即传送先前缓存的位置 数据,然后在 变为可用时传送更新的位置数据。因此,在采取任何操作之前,检查任何位置对象的 时间戳总是一个好主意。如果两个 位置服务都同时启用,则它们使用相同的一组委托方法传送事件 。

其实,如果你取消注释locationManager = nil;它应该帮助,但如果你想用你的checkingForLocation属性,你应该同步的分配。 @synchronized(self)是这种情况下最简单的方法。