我写信给你是因为我遇到了一个非常奇怪的错误。 我试图在我的应用程序上添加GMS,最后,当我必须获取设备位置时,我遇到了这个崩溃:
由于未捕获的异常而终止应用程序' NSInternalInconsistencyException',原因:'类GMSMapView的实例0x7ff7fd82def0已取消分配,而键值观察者仍在其中注册。目前的观察资料:( 上下文:0x0,属性:0x7ff7fdc2f470>
代码在此初始化:
self.mapView.myLocationEnabled = YES;
self.mapView.mapType = kGMSTypeNormal;
self.mapView.settings.compassButton = YES;
self.mapView.settings.myLocationButton = YES;
//=> Listen to the myLocation property of GMSMapView.
[self.mapView addObserver:self
forKeyPath:@"myLocation"
options:NSKeyValueObservingOptionNew
context:NULL];
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context
{
if ([keyPath isEqualToString:@"myLocation"] && [object isKindOfClass:[GMSMapView class]])
{
appDelegate().curUserLocation = [change objectForKey:NSKeyValueChangeNewKey];
[self.mapView animateToCameraPosition:[GMSCameraPosition cameraWithLatitude:self.mapView.myLocation.coordinate.latitude
longitude:self.mapView.myLocation.coordinate.longitude
zoom:15]];
}
}
仍然没有成功。我把断点放在observerValueForKey方法中,一旦从这里出来,就会出现崩溃。无法得到这个想法。
我也删除了观察者:
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
[self.mapView removeObserver:self forKeyPath:@"myLocation"];
//=> Set map delegate to nil (to avoid: mapView:regionDidChangeAnimated:]: message sent to deallocated instance )
self.mapView.delegate = nil;
self.mapView = nil;
}
并没有成功。
任何人都可以帮我吗?我尝试了所有可能的解决方案,但没办法。
提前致谢!
答案 0 :(得分:2)
评论中已经说过了...... GMSMapView必须是Strong
如果您不致电requestWhenInUseAuthorization
我建议你只使用CLLocationManager代替KVO ......但这是你的决定。
Attached my example - 我用2个示例修改了Google示例...
如果您有任何问题......请告诉我
PS别忘了添加API密钥
快乐的编码!
更新
如果你是startUpdatingLocation ..请不要忘记在stopUpdatingLocation
的某个地方停止它..让我们在ViewDidDisapear
答案 1 :(得分:2)
如果您在 viewWillAppear 中注册,请使用 viewWillDisappear 删除观察者。
如果您在 viewDidLoad 内注册,请使用 deinit 取消注册观察者。始终使用计数器部分进行注册和取消注册,这应该没问题
Swift 3
deinit {
mapView.removeObserver(self, forKeyPath: "myLocation")
}