Elton's Blog

为什么要在addsubview:一个view对象后,release它

by on 十.24, 2009, under iPhone

先看代码:

1
2
3
IMGView *imgView = [[IMGView alloc] initWithFrame:CGRectMake(10, 0, 300, 300)];
[self.view addSubview:imgView];
[imgView release];

为什么imgView要release呢?可能很多人跟我一样,之前不是很清楚。 我们逐行分析一下

第一行,alloc一次,imgView对象retainCount为1,
第二行,addSubview一次,此方法会把你传过去的对象retain一次,那么此时它的retainCount为2。self.view变为它的第二个待有者。参考:The receiver retains view. If you use removeFromSuperview to remove view from the view hierarchy, view is released.
第三行,调用release方法,此处释放对imgView的所有权,retainCount减1。

到语言句尾imgView的所有者只剩下self.view,并且它的retainCount仅为1。内存管理第一铁则,谁retain(alloc,copy)谁release(autorelease)。上述的做法也是为了符合这一准则。





:, , , ,

5 Comments for this entry

Leave a Reply

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit my friends!

A few highly recommended friends...