2010-11-01 76 views
0

我正在实现基于MKMapView的应用程序。在我点击一个别针时,我正在使用观察者。观察者代码如下,使用KVO时出现异常

[annView  addObserver:self 
     forKeyPath:@"selected" 
     options:NSKeyValueObservingOptionNew 
     context:@"ANSELECTED"]; 

它正在为例外,但过一段时间就越来越例外“EXC_BAD_ACCESS”。我的日志如下,它显示我泄漏的内存。我需要释放服务器吗?如果我 ?那么我应该在哪里发布这个?你们能帮我解决吗?

An instance 0x1b21f0 of class MKAnnotationView is being deallocated while key value observers are still registered with it. Observation info is being leaked, and may even become mistakenly attached to some other object. Set a breakpoint on NSKVODeallocateBreak to stop here in the debugger. Here's the current observation info: 

( 语境:0x2b588,物业:0x1acaa0>

由于提前, S.

+0

而是志愿的,为什么不直接使用didSelectAnnotationView委托方法? – Anna 2010-11-01 18:10:54

回答

3

它工作正常,但有一段时间它得到异常'EXC_BAD_ACCESS'。我的日志如下,它显示我泄漏的内存。 ...

An instance 0x1b21f0 of class MKAnnotationView is being deallocated while key value observers are still registered with it. 

这是泄漏的对面。它被解除分配;泄漏是当对象将永远不会被解除分配时

问题在于它正在被释放,而其他东西仍然在观察它。任何仍在观察该对象的事物也可能在稍后发送其他消息;当它发生时,这些消息将转到一个死对象(导致您看到的崩溃,这发生在该消息之后)或到另一个对象。

如果观察MKAnnotationView的对象拥有它并释放它,它需要在释放它之前将其自身作为观察者移除。如果它不拥有它,它可能应该。

1

你必须停止观察注解视图中,释放它之前:

[annView removeObserver:self forKeyPath:@"selected"]; 
+0

我用过这个,但是仍然有内存异常 – sekhar 2010-11-01 10:07:00

+0

然后我们需要看到更多的代码。 – zoul 2010-11-01 10:42:06

0

我知道这是相当古老的,但我看到这个代码在stackoverflow和其他仓库中使用了很多,这里是解决问题的办法。

你应该以存储到您的注释的参考在您的视图控制器类中创建一个NSMutableArray伊娃查看:

MyMapViewController <MKMapViewDelegate> { 
NSMutableArray *annot; 

}

初始化它在你的viewDidLoad中,在你- (MKAnnotationView *) mapView:(MKMapView *)theMapView viewForAnnotation:(id <MKAnnotation>) annotation 你应该在AnnView addObserver代码之前将MKAnnotationView添加到可变数组本身:

if(nil == annView) { 
    annView = [[MyAnnotationView alloc] initWithAnnotation:myAnnotation reuseIdentifier:identifier]; 
    [annot addObject:annView]; 
} 


[annView addObserver:self 
      forKeyPath:@"selected" 
      options:NSKeyValueObservingOptionNew 
      context:(__bridge void *)(GMAP_ANNOTATION_SELECTED)]; 

然后,在你viewDidDisappear方法,你可以遍历数组,并手动删除所有的观察员

//remove observers from annotation 
for (MKAnnotationView *anView in annot){ 
    [anView removeObserver:self forKeyPath:@"selected"]; 
} 

[annot removeAllObjects]; 

[super viewDidDisappear:animated]; 
相关问题