【问题标题】:iPhone mapView / mapKit using removeAnnotation & addAnnotation results in memory leak?iPhone mapView / mapKit 使用 removeAnnotation 和 addAnnotation 导致内存泄漏?
【发布时间】:2010-02-04 22:34:36
【问题描述】:

要在 mapView 上更新 GPS 指示器的位置...

[mapView removeAnnotation:myGpsAnnotation];
[myGpsAnnotation release];
myGpsAnnotation = nil;
myGpsAnnotation = [[MapLocationAnnotation alloc] initWithCoordinate:region.center annotationType:MapAnnotationTypeGps title:MAP_ANNOTATION_TYPE_GPS];
[mapView addAnnotation:myGpsAnnotation];

...我看到 Instruments(模拟器)中的净内存在缓慢攀升。没有“泄漏”信号,但“Net Bytes”和“#Net”缓慢增加......除非这段代码被注释掉。所以我 100% 确定这是有问题的代码。

但是如果我执行以下操作...

[mapView removeAnnotation:myGpsAnnotation];
[myGpsAnnotation release];
myGpsAnnotation = nil;
myGpsAnnotation = [[MapLocationAnnotation alloc] initWithCoordinate:region.center annotationType:MapAnnotationTypeGps title:MAP_ANNOTATION_TYPE_GPS];
[mapView addAnnotation:myGpsAnnotation];
[mapView removeAnnotation:myGpsAnnotation];
[mapView addAnnotation:myGpsAnnotation];
[mapView removeAnnotation:myGpsAnnotation];
[mapView addAnnotation:myGpsAnnotation];

...然后“Net Bytes”和“#Net”增加得更快。这可能不是我的错误,我正在尝试追踪 MapKit 中的泄漏吗?我真的在泄漏内存吗?同样,“泄漏”下什么也没有出现,但我不明白为什么净值会不断攀升。

感谢您的帮助,-戈德

【问题讨论】:

  • 我对你如何做到这一点很感兴趣,如果你有一个和平的代码,你可以粘贴它,就像我们可以学习一样,THX 对我们有很多帮助......跨度>

标签: iphone memory-leaks annotations mapkit android-mapview


【解决方案1】:

你的发布周期是错误的:

myGpsAnnotation = [[MapLocationAnnotation alloc] initWithCoordinate:region.center annotationType:MapAnnotationTypeGps title:MAP_ANNOTATION_TYPE_GPS]; 
//retain count = 1

[mapView addAnnotation:myGpsAnnotation]; 
//retain count = 2 (the map does an extra retain)

[myGpsAnnotation release]; 
//retain count = 1
myGpsAnnotation = nil; //not really necessary

[mapView removeAnnotation:myGpsAnnotation]; 
//retain count = 0 -> dump (you can do this on the original place; I put it here to show the cycle)

PS。您看到的内存增加可能来自 annotationVIEWS。这些由地图缓存。如果您仍然看到 mem 增加,可能您的观点 dequeueing 是错误的。

PPS。您是否考虑过为注释设置新位置。如果位置是唯一改变的东西,那就容易多了。

myGpsAnnotation.coordinate = region.center;

【讨论】:

    【解决方案2】:

    您应该首先了解收集的工作原理。

    添加和对象到集合将保留它。
    从集合中移除一个对象会释放它。

    在你的情况下,它是一个地图视图:


    1. 将注解添加到地图视图后,如果您拥有该引用,则应将其释放。
    2. 从地图视图中删除注释后不需要释放它。

     MyClass *obj=[[MClass alloc] init];
     [mapview addObject:obj];
     [obj release];
     ...
     [mapview removeAnnotation:obj];
    

    就是这样。此处无需发布。

    【讨论】:

      【解决方案3】:

      如果您在模拟器上进行测试时观察到这一点,请不要担心。似乎地图工具包在模拟器上运行时在内存中缓存地图图块,而在设备上,它使用 SQLite 来存储地图图块,而不是设备上有限的 RAM。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-04-18
        • 1970-01-01
        • 2023-03-22
        • 2013-09-07
        • 2017-04-20
        • 1970-01-01
        • 2016-06-05
        相关资源
        最近更新 更多