开发者

Release an object without a pointer?

I’ve just started developing for iPhone and am trying to get my head around memory management. I made a small program that shows a map and an annotation on the map. For the annotation I made a simple class that implements the MKAnnotation protocol.

To create and add the annotation I wrote this:

[self.myMapView addAnnotation:[[MyAnnotation alloc] init]];

It worked fine until I tried to release the object. Nothing to release. This is what I would have done in C#, I guess it doesn’t work without garbage collection?

So is this the only way to do it?

MyAnnotation *myA开发者_运维知识库nnotation = [[MyAnnotation alloc] init];

[self.myMapView addAnnotation: myAnnotation];

[myAnnotation release];


[self.myMapView addAnnotation:[[[MyAnnotation alloc] init] autorelease]];


Yes, that is the accepted way to handle a situation like this. You could have also called autorelease as in codelark's answer, but on the limited memory environment of the iPhone, autoreleasing can sometimes cause problems due to objects lingering for a while before they are finally released. It's a good practice to avoid autorelease where possible.


Everybody, thanks for the answers.

It seems to me that this code is the one that most resembles the solution I was thinking of in the first place.

[self.myMapView addAnnotation:[[[MyAnnotation alloc] init] autorelease]];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜