我正在使用下面的代码为注解创建一个别针:
- (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中的Analyze在这段代码中显示了内存泄漏。事实上,我也看到了它,因为我分配了对象,然后没有释放它。如何避免这里的内存泄漏?
发布于 2011-08-18 17:26:58
你没有写,但我认为分析器会告诉你它在这里泄漏了什么:
MKPinAnnotationView *annView=[[MKPinAnnotationView alloc]
initWithAnnotation:annotation
reuseIdentifier:@"currentloc"];这是因为你需要自动释放项:
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];发布于 2011-08-18 17:29:26
事实上,我也看到了它,因为我分配了对象,然后没有释放它。
关于泄漏的原因,你是对的。如果你需要从一个方法返回一个分配的对象,那么这个想法就是自动释放它。
- (MyClass *)getObject {
MyClass *obj = [[MyClass alloc] init];
return [obj autorelease];
}然后,如果需要,您将在caller中保留返回的对象。
或者以这样一种方式命名方法,即返回的对象需要在caller中释放。然后在调用者中释放。
https://stackoverflow.com/questions/7105061
复制相似问题