问题
I am looking at this code lifted straight from the MapViewController.m file in the CurrentAddress sample available on Apple's web site:
- (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];
}
I am wondering what the function is of the autorelease when allocating the object. (The reverseGeocoder is an ivar in the MapViewController class set up with the retain property.) I have code similar to this in my application, and it seems to work either way.
回答1:
Setting your reverseGeocoder
property increments the retain count (+1), but since you're creating the object with alloc
+init
(+1), you need to autorelease
(-1) so that you do not end up with a 2 retain count.
It does work either way, the only difference is that when you do not autorelease
, you leak.
The reverseGeocoder is an ivar
It sure is, but note that when you're using the self.reverseGeocoder
form, you're not accessing the ivar directly - instead, you're calling the relevant setReverseGeocoder:
function, that is either written by yourself or @synthesized by the compiler.
See: http://developer.apple.com/library/mac/#documentation/cocoa/conceptual/MemoryMgmt/MemoryMgmt.html
And: What equivalent code is synthesized for a declared property?
来源:https://stackoverflow.com/questions/5836660/mkreversegeocoder-autorelease-release-question-in-apples-currentaddress-sample