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

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)。上述的做法也是为了符合这一准则。

猜你喜欢

转载自lixiangyu.iteye.com/blog/1620145