【发布时间】:2016-11-17 22:24:51
【问题描述】:
下面是我的代码的一些sn-ps
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 的调用仍将checkingForLocation 视为YES。那里有竞争条件吗?
通过搜索其他 SO 问题,我发现设置 locationManager = nil 将停止对 didUpdateLocations 的额外调用,它确实解决了我的问题,但没有真正的解释。似乎 stopUpdatingLocation 应该解决这个问题。非常感谢任何见解。
谢谢,
【问题讨论】:
-
你在哪里打电话给
[locationManager startUpdatingLocation]; checkingForLocation = YES;? -
@OgreSwamp 我在按下按钮时调用它。为了清楚起见,我在上面添加了 IBAction 方法。
标签: ios objective-c cllocationmanager