我正在查看直接从 CurrentAddress sample 中的 MapViewController.m 文件提取的这段代码可以在 Apple 的网站上找到:
- (void)dealloc
{
[reverseGeocoder release];
[mapView release];
[getAddressButton release];
[super dealloc];
}
- (IBAction)reverseGeocodeCurrentLocation
{
self.reverseGeocoder =
[[[MKReverseGeocoder alloc] initWithCoordinate:mapView.userLocation.location.coordinate] autorelease];
reverseGeocoder.delegate = self;
[reverseGeocoder start];
}
我想知道分配对象时自动释放的功能是什么。 (reverseGeocoder 是使用保留属性设置的 MapViewController 类中的一个 ivar。)我的应用程序中有与此类似的代码,它似乎可以以任何一种方式工作。
最佳答案
设置您的 reverseGeocoder
属性会增加保留计数 (+1),但是由于您使用 alloc
+init
创建对象 ( +1),你需要autorelease
(-1) 这样你就不会得到 2 个保留计数。
这两种方式都有效,唯一的区别是当您不 autorelease
时,您会泄漏。
The reverseGeocoder is an ivar
确实如此,但请注意,当您使用 self.reverseGeocoder
表单时,您并没有直接访问 ivar - 相反,您正在调用相关的 setReverseGeocoder:
函数,要么是你自己写的,要么是编译器@synthesized。
参见:http://developer.apple.com/library/mac/#documentation/cocoa/conceptual/MemoryMgmt/MemoryMgmt.html
并且: What equivalent code is synthesized for a declared property?
关于ios - Apple 的 CurrentAddress 示例中的 MKReverseGeocoder autorelease/release 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5836660/