views:

84

answers:

5

I stumbled into a problem when I hit the "build and analyze" button on the Build menu in my Xcode. The analysis suggest me to release a variable that I wish later on to be returned. The code is like following:

- (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>) annotation{

     //I do some other thing here

     MKPinAnnotationView *annView=
        [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"addressLocation"];

     //I do some other thing here

     return annView;
}

I can I release annView and return it without causing any problem?

+1  A: 

Have you looked at autorelease?

Abizern
I thought of it. I am just not sure if it works well in this case. Please let me know if I am wrong, since I am a very newbie in objective-c.
Winston Chen
@Winston Chen: This is exactly what `autorelease` is for.
dreamlax
A: 

Based on what you have posted here, no, you cant release it and then return it. The caveat being if you are setting any other retains on the object in your other code. You can easily check this before returning with an nslog statement.

NSLog(@"retainCount:%d", [annView retainCount]);

adam0101
Checking the retain count is not a good idea. It doesn't give you an accurate picture of anything.
Chuck
+6  A: 

This is precisely what autorelease is intended for. That method should autorelease it.

I'd suggest reading the memory management guide if you're unclear about this sort of thing. It's pretty short and explains all this stuff very well. Once you understand that guide, you won't ever have to wonder again.

Chuck
+1  A: 

Useful Lynda.com video explaining autorelease pools is available here:

http://creativemac.digitalmedianet.com/articles/viewarticle.jsp?id=1003156
Matt
Thank you. That's very helpful.
Winston Chen
A: 

The autorelease pool is the perfect thing for you to use. When you are returning the variable, do the following:

return [myVariable autorelease];

A lot of apple's methods use this. Most static constructors on apple's classes such as [NSString stringWithFormat:] return autoreleased variables.

Cappuccino Plus Plus