如果我不再使用 MKMapView,为什么在释放 MKMapView 后会崩溃? [英] Why am I crashing after MKMapView is freed if I'm no longer using it?
问题描述
我有一个 MKMapView
.有时在我的视图控制器被关闭后,我会得到一个 EXC_BAD_ACCESS
.
I have a MKMapView
. Sometimes after my view controller is dismissed, I'll get a EXC_BAD_ACCESS
.
我打开了NSSZombies
,它看起来像MKMapView
的委托——我的视图控制器!— 正在被调用,尽管 MKMapView
和 UIViewController
子类都被释放了.我已经检查过了,我的内存管理是正确的.
I turned on NSSZombies
and it looks like the MKMapView
's delegate — my view controller! — is being called, despite both the MKMapView
and UIViewController
subclass being freed. I've checked, and my memory management is correct.
怎么回事?
推荐答案
这是因为 MKMapView
的工作方式.有一个操作未决,所以 MapKit 保留了 MKMapView
并且它实际上还没有被释放.那本身不是问题.问题是它仍在向您的代表发送消息.
This is because of the way MKMapView
works. There's an operation pending, so MapKit is retaining the MKMapView
and it hasn't actually been deallocated yet. That isn't itself a problem. The problem is that it's still sending messages to your delegate.
解决方法很简单:作为视图控制器清理的一部分,将地图视图的委托设置为 nil
,这将阻止 MKMapView
向其发送消息.
The workaround is simple: As part of your view controller's cleanup set the map view's delegate to nil
, which will prevent MKMapView
from sending messages to it.
这在 MKMapViewDelegate 协议参考中有记录:
在释放已为其设置委托的 MKMapView 对象之前,请记住将该对象的委托属性设置为 nil.您可以在 dealloc 方法中执行此操作,您可以在该方法中处理地图视图.
Before releasing an MKMapView object for which you have set a delegate, remember to set that object’s delegate property to nil. One place you can do this is in the dealloc method where you dispose of the map view.
也给奥斯卡一个赞,就在下面,他在这里提供了文档引用.
Give Oscar an upvote as well, just below, who provided the documentation quote here.
鉴于 ARC,我建议这意味着您应该在视图控制器的 dealloc
中将地图视图的委托设置为 nil
.
Given ARC, I suggest this means you should set your map view's delegate to nil
in your view controller's dealloc
.
这篇关于如果我不再使用 MKMapView,为什么在释放 MKMapView 后会崩溃?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!