先看代码:
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)。上述的做法也是为了符合这一准则。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有