简体   繁体   English

iPhone:添加到子视图时内存的工作原理

[英]iPhone: How Memory works when adding to subview

A general question: When you add an item to an UIView, does that increase the owner count by 1? 一般问题:当您向UIView添加项目时,是否会将所有者计数增加1? Does the main view that you added the item to now becomes an owner as well? 您现在添加项目的主视图是否也成为了所有者?

Example: 例:

mainView = [[UIView alloc] init];
UILabel *label = [[UILabel alloc] init];
[mainView addSubview:label] //does this increase owner count by 1?
[label release] //and this decreases it by 1?

You release what you retain/init. 释放保留/ init的内容。

When you call addSubview: , it increases the retain count (or as you say owner count). 当您调用addSubview: ,它会增加保留计数(或者如您所说的所有者计数)。 But that increase belongs to mainView . 但是这种增加属于mainView So it is up to mainView to release the subview some point in the future, not you. 所以mainView将来某个点发布子视图是由mainView决定的。

So when you init the label it increases the retain count to 1. When you call addSubview:label it increases the retain count by 1, to 2. Then you release the label, decreasing the retain count back to 1 and counteracting you're previous init. 因此,当您init标签时,它会将保留计数增加到1.当您调用addSubview:label它会将保留计数增加1,然后再释放2.然后释放标签,将保留计数减少回1并抵消先前在里面。

Then when the label is removed from the mainView its retain count will go back down to 0 and it will be deallocated. 然后,当从mainView中删除标签时,其保留计数将返回到0并且将被取消分配。

Never use the method retainCount , whether you're just observing it, or acting on it. 永远不要使用方法retainCount ,无论您只是观察它还是采取行动。 This method will not display what you expect because of a lot of behind the scenes code. 由于很多幕后代码,此方法不会显示您所期望的内容。 Just don't use retainCount . 只是不要使用retainCount

Subviews are stored in a NSArray which sends a retain to every object added. 子视图存储在NSArray中,它会为添加的每个对象发送一个保留。 In principle, yes the retain count goes as you expect but in reality you can never observe the retain count reliably because of all the retains and releases that occur behind the scenes in the API itself. 原则上,是的,保留计数按预期进行,但实际上,由于API本身幕后发生的所有保留和释放,您实际上永远无法可靠地观察到保留计数。 Trying to track the retain count directly will just lead to grief. 试图直接跟踪保留计数只会导致悲伤。

It's better to just follow the rule of if you create an object with new or alloc-init then you release it. 如果你使用new或alloc-init创建一个对象然后释放它,那么最好遵守规则。 If you don't do the former, you don't do the later. 如果你不做前者,你就不要做了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM