Objective-C 中的retainCount 是什么?
我有一个 UITableView
作为我的第一个屏幕,带有 UINavigation
控制器。
在我的第一个屏幕中,我 NSLog(@"Home Screen keep Count=%d",[self keepCount]);
,当调用 viewDidLoad
时,它会记录 6。
它是否正确?
I have a UITableView
as my first screen with a UINavigation
controller.
In my first screen I NSLog(@"Home Screen retain Count=%d",[self retainCount]);
and it logs 6 in when its viewDidLoad
is called.
Is this correct?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
keepCount 是对象上未决的所有权声明的数量。
如果您使用名称以“alloc”或“new”开头或包含“copy”(例如,alloc、newObject 或 mutableCopy)的方法创建对象,或者向其发送保留消息,则您将获得该对象的所有权。 所有这些都会增加保留计数。
您可以使用“release”或“autorelease”放弃所有权。 这些会减少保留计数。
但是,您永远不应该关注保留计数的值,它往好了说是令人困惑的,往坏了说是误导性的。 只需遵循内存管理规则 - 当您需要保留对对象的引用并在完成后放弃所有权,这样就不会有问题。
如果您正在查看retainCount,那么您就以错误的方式处理事情,并且只会让自己更加困惑。
The retainCount is the number of ownership claims there are outstanding on the object.
You take ownership of an object if you create it using a method whose name begins with “alloc” or “new” or contains “copy” (for example, alloc, newObject, or mutableCopy), or if you send it a retain message. All of these increment the retainCount.
You relinquish ownership with using “release” or “autorelease”. These decrement the retainCount.
However you should never pay any attention to the value of retainCount, it is at best confusing, at worst misleading. Simply follow the memory management rules - take ownership when you need to keep a reference to an object and relinquish ownership when you are finished, and you wont have a problem.
If you are looking at retainCount, you are going about things the wrong way, and you will simply confuse yourself further.
听起来不错。 为什么会出错呢?
一般来说,试图从保留计数中确定事情是一个坏主意。 对于可以保留对象的次数没有任何规则。 唯一的规则是每个保留必须与释放相平衡。
It sounds fine. Why would it be wrong?
In general, trying to determine things from the retain count is a bad idea. There are no rules about the amount of times you can retain an object. The only rule is that each retain must be balanced with a release.