保留目标 C 中的计数返回 -1
我是 Objective C 的新手,我有一个 NSMutableArray,其中有 3 个对象,然后我尝试打印数组的保留计数。为什么最终retainCount返回-1?谢谢
NSLog(@"myArray has retain count of %d", [myArray retainCount]);
[myArray release];
NSLog(@"myArray has retain count of %d", [myArray retainCount]);
控制台结果:
2010-10-17 11:58:06.407 TestRetainCount [527:a0f] myArray has retain count of 1
2010-10-17 11:58:06.407 TestRetainCount [527:a0f] myArray has retain count of -1
I'm new to objective C, I have a NSMutableArray with 3 objects in it, then I try to print the retainCount of the array. Why the final retainCount return -1? Thanks
NSLog(@"myArray has retain count of %d", [myArray retainCount]);
[myArray release];
NSLog(@"myArray has retain count of %d", [myArray retainCount]);
Result from console:
2010-10-17 11:58:06.407 TestRetainCount [527:a0f] myArray has retain count of 1
2010-10-17 11:58:06.407 TestRetainCount [527:a0f] myArray has retain count of -1
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对象被释放后(这可能发生在释放之后),您不能再依赖其数据的完整性。您试图在保留计数变得无效后信任它。
一般而言,不要使用保留计数。曾经。使用内存管理编程指南中的规则,您将始终获得正确的引用计数。
After an object has been deallocated (which may happen after a release), you can no longer rely on its data being intact. You're trying to trust the retain count after it has become invalid.
On a general note, don't use the retain count. Ever. Use the rules in the memory management programming guide, and you'll always get the reference counting correct.
格雷厄姆·李回答了针对您的示例的问题。
不是特定于您的示例,而是您的问题(主题):
UINT_MAX
通常用于表示不使用引用计数的对象(例如,永远不会释放,例如单例),或自定义引用计数的实现。Graham Lee answered the question specific to your example.
not specific to your example, but to your question (subject):
UINT_MAX
is often used to denote an object which uses no reference counting (e.g., is never deallocated, such as a singleton), or a custom reference counting implementation.由于定时自动释放对象,无法依赖准确的保留计数。也就是说,计算您的 alloc/init、new、retains 等...并与相应的版本匹配。
Can't rely on an accurate retainCount because of the timing autoreleased objects. That said, count your alloc/init, new, retains, etc... and match with corresponding release.