Apple 的 CurrentAddress 示例中的 MKReverseGeocoder 自动发布/发布问题

Posted

技术标签:

【中文标题】Apple 的 CurrentAddress 示例中的 MKReverseGeocoder 自动发布/发布问题【英文标题】:MKReverseGeocoder autorelease/release question in Apple's CurrentAddress sample 【发布时间】:2011-04-29 19:45:03 【问题描述】:

我正在查看直接从 Apple 网站上的 CurrentAddress sample 中的 MapViewController.m 文件中提取的代码:

- (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,设置了 retain 属性。)我的应用程序中有类似的代码,它似乎可以工作。

【问题讨论】:

【参考方案1】:

设置 reverseGeocoder 属性会增加保留计数 (+1),但由于您使用 alloc+init (+1) 创建对象,因此您需要 autorelease (-1) 所以你最终不会得到 2 个保留计数。

无论哪种方式都可以,唯一的区别是当你autorelease时,你会泄漏。

reverseGeocoder 是一个 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?

【讨论】:

以上是关于Apple 的 CurrentAddress 示例中的 MKReverseGeocoder 自动发布/发布问题的主要内容,如果未能解决你的问题,请参考以下文章