MKAnnotationView:内存泄漏

时间:2011-08-18 09:17:42

标签: ios ios4 memory-leaks mapkit mkannotationview

我正在使用以下代码为注释创建一个引脚:

- (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)           annotation
{
    MKPinAnnotationView *annView=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"currentloc"];
    annView.pinColor = MKPinAnnotationColorGreen;
    annView.animatesDrop=TRUE;
    annView.canShowCallout = YES;
    annView.calloutOffset = CGPointMake(-5, 5);

    return annView;
}

一切都很完美,但是在XCode中的分析显示了此代码中的内存泄漏。事实上,我看到它也是因为我分配了对象然后没有释放它。 我怎样才能避免内存泄漏?

2 个答案:

答案 0 :(得分:3)

你没写过,但我认为分析器会告诉你它在这里泄漏了什么:

MKPinAnnotationView *annView=[[MKPinAnnotationView alloc] 
                                 initWithAnnotation:annotation 
                                    reuseIdentifier:@"currentloc"];

那是因为你需要autorelease项目:

MKPinAnnotationView *annView=[[[MKPinAnnotationView alloc] 
                                  initWithAnnotation:annotation 
                                     reuseIdentifier:@"currentloc"] autorelease];

<强>更新

此外,您不会重复使用已创建的注释,请尝试执行以下操作:

MKPinAnnotationView *annView = (MKPinAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:@"currentloc"];
if(annView == nil) 
    annView = annView=[[[MKPinAnnotationView alloc] 
                         initWithAnnotation:annotation 
                            reuseIdentifier:@"currentloc"] autorelease];

答案 1 :(得分:1)

  

事实上,我认为它也是因为我分配了对象然后没有释放它。

你说泄漏的原因是正确的。如果你需要从一个方法返回一个分配的对象,那么我们的想法是自动释放它。

- (MyClass *)getObject {
    MyClass *obj = [[MyClass alloc] init];
    return [obj autorelease];
}

然后,如果需要,您将在调用者中保留返回的对象。

或者以这样一种方式命名方法,即显然返回的对象需要在调用者中释放。然后在呼叫者中释放。

相关问题