为什么要在addsubview:一个view对象后,release它
by Elton 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)。上述的做法也是为了符合这一准则。



七月 23rd, 2010 on 13:58
just placed this page on my facebook. it’s a very interesting read for everyone.
七月 24th, 2010 on 19:15
This can be a fantastic write-up thanks for sharing this informative info.. I am going to go to your website frequently for some latest post.
十月 14th, 2010 on 15:08
Thanks for this post.
六月 9th, 2011 on 11:06
看来你的文章突然想到也可以通过产看该实例的retainCount在一个函数处理之后(如addSubView),这样也可以确定时候retain了该实例。
六月 9th, 2011 on 11:06
谢谢你的分享。