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 中的分析显示此代码中存在内存泄漏。事实上,我也看到了这一点,因为我分配了对象,然后没有释放它。 这里如何避免内存泄漏?
I'm using the following code to make a pin for annotation:
- (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;
}
Everything works perfectly, however Analyze in XCode shows memory leak in this code. In fact, I see it too cos I allocated object and then did not released it.
How can I avoid memory leak here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你没有写,但我认为分析器告诉你它在这里泄漏了什么:
那是因为你需要自动释放项:
更新
另外你不重用创建的注释,尝试这样做:
You didn't wrote, but I think analyzer tells you what it leaks here:
Thats because you need autorelease item:
UPDATE
Also you don't reuse created annotations, try do this:
您关于泄漏原因的说法是正确的。如果您需要从方法返回分配的对象,那么想法是自动释放它。
然后,如果需要,您将在调用者中保留返回的对象。
或者以明确返回的对象需要在调用者中释放的方式命名该方法。然后在调用者中释放。
You are right about the reason of the leak. If you need to return an alloced object from a method then the idea is to autorelease that.
Then you will retain the returned object in caller if needed.
Or name the method in such a way that it is clear that the returned object need to be released in caller. And then release in the caller.